code stringlengths 1 1.05M | repo_name stringlengths 6 83 | path stringlengths 3 242 | language stringclasses 222 values | license stringclasses 20 values | size int64 1 1.05M |
|---|---|---|---|---|---|
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "module_mqtt.h"
#include "aiot_state_api.h"
#include "amp_platform.h"
#include "amp_task.h"
#include "aos_system.h"
#include "be_inl.h"
#include "py_defines.h"
#define MOD_STR "MQTT"
#define MQTT_TASK_YIELD_TIMEOUT 200
static char g_mqtt_close_flag = 0;
static aos_sem_t g_mqtt_close_sem = NULL;
static void mqtt_handle_notify(void *pdata)
{
int res;
amp_mqtt_handle_t *amp_mqtt_handle = (amp_mqtt_handle_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx,
amp_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF]);
duk_push_int(ctx, amp_mqtt_handle->res);
duk_push_pointer(ctx, amp_mqtt_handle);
if (duk_pcall(ctx, 2) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
/* free when mqtt connect failed */
if (amp_mqtt_handle->res < 0) {
be_unref(ctx,
amp_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF]);
aos_free(amp_mqtt_handle);
}
duk_gc(ctx, 0);
}
static void mqtt_connect_task(void *pdata)
{
int ret;
amp_mqtt_handle_t *amp_mqtt_handle = NULL;
amp_mqtt_params_t *amp_mqtt_params = (amp_mqtt_params_t *)pdata;
amp_mqtt_handle = aos_malloc(sizeof(amp_mqtt_handle_t));
if (amp_mqtt_handle == NULL) {
amp_debug(MOD_STR, "amp mqtt handle malloc failed \r\n");
aos_free(amp_mqtt_params);
return;
}
amp_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF] =
amp_mqtt_params->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF];
ret = mqtt_client_start(&_mqtt_handle->mqtt_handle, amp_mqtt_params);
if (ret < 0) {
amp_debug(MOD_STR, "mqtt client init failed \r\n");
aos_free(amp_mqtt_params);
aos_free(amp_mqtt_handle);
return;
}
amp_mqtt_handle->res = ret;
/* return aiot_device_handle */
amp_task_schedule_call(mqtt_handle_notify, amp_mqtt_handle);
while (!g_mqtt_close_flag) {
aos_msleep(1000);
}
aos_free(amp_mqtt_params);
aos_free(amp_mqtt_handle);
aos_sem_signal(&g_mqtt_close_sem);
aos_task_exit(0);
}
static duk_ret_t native_mqtt_start(duk_context *ctx)
{
int ret;
amp_mqtt_params_t *mqtt_params = NULL;
aos_task_t mqtt_task;
/* check paramters */
if (!duk_is_object(ctx, 0) || !duk_is_function(ctx, 1)) {
amp_warn(MOD_STR, "parameter must be object and function\n");
ret = -1;
goto out;
}
/* get device certificate */
duk_get_prop_string(ctx, 0, "host");
duk_get_prop_string(ctx, 0, "port");
duk_get_prop_string(ctx, 0, "client_id");
duk_get_prop_string(ctx, 0, "username");
duk_get_prop_string(ctx, 0, "password");
duk_get_prop_string(ctx, 0, "keepaliveSec");
if (!duk_is_string(ctx, -6) || !duk_is_number(ctx, -5) ||
!duk_is_string(ctx, -4) || !duk_is_string(ctx, -3) ||
!duk_is_string(ctx, -2) || !duk_is_number(ctx, -1)) {
amp_warn(MOD_STR,
"Parameter 1 must be an object like {host: string, "
"port: uint, client_id: string, username: string, "
"password: string, keepalive_interval: uint}\n");
ret = -2;
duk_pop_n(ctx, 6);
goto out;
}
mqtt_params = (amp_mqtt_params_t *)aos_malloc(sizeof(amp_mqtt_params_t));
if (!mqtt_params) {
amp_error(MOD_STR, "allocate memory failed\n");
goto out;
}
mqtt_params->host = duk_get_string(ctx, -6);
mqtt_params->port = duk_get_number(ctx, -5);
mqtt_params->clientid = duk_get_string(ctx, -4);
mqtt_params->username = duk_get_string(ctx, -3);
mqtt_params->password = duk_get_string(ctx, -2);
mqtt_params->keepaliveSec = duk_get_number(ctx, -1);
amp_debug(MOD_STR, "host: %s, port: %d\n", mqtt_params->host,
mqtt_params->port);
amp_debug(MOD_STR, "client_id: %s, username: %s, password: %s\n",
mqtt_params->clientid, mqtt_params->username,
mqtt_params->password);
duk_dup(ctx, 1);
// init_params->js_cb_ref = be_ref(ctx);
mqtt_params->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF] = be_ref(ctx);
/* create task to IOT_MQTT_Yield() */
ret = aos_task_new_ext(&mqtt_task, "amp mqtt task", mqtt_connect_task,
mqtt_params, 1024 * 4, MQTT_TSK_PRIORITY);
if (ret < 0) {
amp_warn(MOD_STR, "jse_osal_create_task failed\n");
be_unref(ctx, mqtt_params->js_cb_ref[MQTT_JSCALLBACK_START_CLIENT_REF]);
aos_free(mqtt_params);
ret = -4;
}
out:
duk_push_int(ctx, ret);
return 1;
}
/* subscribe */
static duk_ret_t native_mqtt_subscribe(duk_context *ctx)
{
int res = -1;
amp_mqtt_handle_t *amp_mqtt_handle = NULL;
const char *topic = NULL;
uint8_t qos = 0;
int js_cb_ref = 0;
if (!duk_is_pointer(ctx, 0) || !duk_is_object(ctx, 1) ||
!duk_is_function(ctx, 2)) {
amp_warn(MOD_STR, "parameter must be (pointer, object) \r\n");
goto out;
}
amp_mqtt_handle = duk_get_pointer(ctx, 0);
if (amp_mqtt_handle == NULL) {
amp_warn(MOD_STR, "mqtt handle is null \r\n");
goto out;
}
duk_get_prop_string(ctx, 1, "topic");
duk_get_prop_string(ctx, 1, "qos");
if (!duk_is_number(ctx, -1) || !duk_is_string(ctx, -2)) {
amp_warn(MOD_STR, "invalid params \r\n");
duk_pop_n(ctx, 2);
goto out;
}
qos = duk_get_number(ctx, -1);
topic = (char *)duk_get_string(ctx, -2);
duk_dup(ctx, 2);
js_cb_ref = be_ref(ctx);
amp_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_SCRIBE_TOPIC_REF] = js_cb_ref;
res = aiot_mqtt_sub(amp_mqtt_handle->mqtt_handle, topic, NULL, qos, NULL);
if (res < 0) {
amp_error(MOD_STR, "aiot app mqtt subscribe failed\n");
}
out:
duk_push_int(ctx, res);
return 1;
}
/* unsubscribe */
static duk_ret_t native_mqtt_unsubscribe(duk_context *ctx)
{
int res = -1;
amp_mqtt_handle_t *amp_mqtt_handle = NULL;
const char *topic;
uint8_t qos = 0;
int js_cb_ref = 0;
if (!duk_is_pointer(ctx, 0) || !duk_is_string(ctx, 1) ||
!duk_is_function(ctx, 2)) {
amp_warn(MOD_STR, "parameter must be (pointer, string, function) \r\n");
goto out;
}
amp_mqtt_handle = duk_get_pointer(ctx, 0);
if (amp_mqtt_handle == NULL) {
amp_warn(MOD_STR, "mqtt handle is null \r\n");
goto out;
}
topic = (char *)duk_get_string(ctx, 1);
duk_dup(ctx, 2);
js_cb_ref = be_ref(ctx);
amp_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_UNSCRIBE_TOPIC_REF] = js_cb_ref;
amp_debug(MOD_STR, "unsubscribe topic: %s \r\n", topic);
res = aiot_mqtt_unsub(amp_mqtt_handle->mqtt_handle, topic);
if (res < 0) {
amp_error(MOD_STR, "aiot app mqtt unsubscribe failed\n");
}
out:
duk_push_int(ctx, res);
return 1;
}
/* publish */
static duk_ret_t native_mqtt_publish(duk_context *ctx)
{
int res = -1;
amp_mqtt_handle_t *amp_mqtt_handle = NULL;
const char *topic;
const char *payload;
uint16_t payload_len = 0;
uint8_t qos = 0;
int js_cb_ref = 0;
if (!duk_is_pointer(ctx, 0) || !duk_is_object(ctx, 1) ||
!duk_is_function(ctx, 2)) {
amp_warn(MOD_STR, "parameter must be (pointer, object, function) \r\n");
goto out;
}
amp_mqtt_handle = duk_get_pointer(ctx, 0);
if (amp_mqtt_handle == NULL) {
amp_warn(MOD_STR, "mqtt handle is null \r\n");
goto out;
}
duk_get_prop_string(ctx, 1, "topic");
duk_get_prop_string(ctx, 1, "payload");
duk_get_prop_string(ctx, 1, "qos");
if (!duk_is_string(ctx, -3) || !duk_is_string(ctx, -2) ||
!duk_is_number(ctx, -1)) {
amp_warn(MOD_STR, "invalid params \r\n");
duk_pop_n(ctx, 3);
goto out;
}
qos = duk_get_number(ctx, -1);
payload = (char *)duk_get_string(ctx, -2);
topic = (char *)duk_get_string(ctx, -3);
payload_len = strlen(payload);
duk_dup(ctx, 2);
js_cb_ref = be_ref(ctx);
amp_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_PUBLISH_REF] = js_cb_ref;
amp_debug(MOD_STR, "publish topic: %s, payload: %s, qos is: %d \r\n", topic,
payload, qos);
res = aiot_mqtt_pub(amp_mqtt_handle->mqtt_handle, topic, payload,
payload_len, qos);
if (res < 0) {
amp_error(MOD_STR, "aiot app mqtt publish failed \r\n");
}
out:
duk_push_int(ctx, res);
return 1;
}
static duk_ret_t native_mqtt_close(duk_context *ctx)
{
int res = -1;
int js_cb_ref = 0;
amp_mqtt_handle_t *amp_mqtt_handle = NULL;
if (!duk_is_pointer(ctx, 0) || !duk_is_function(ctx, 1)) {
amp_warn(MOD_STR, "parameter must be pointer function \r\n");
goto out;
}
amp_mqtt_handle = duk_get_pointer(ctx, 0);
if (amp_mqtt_handle == NULL) {
amp_warn(MOD_STR, "mqtt client is null \r\n");
goto out;
}
duk_dup(ctx, 1);
js_cb_ref = be_ref(ctx);
amp_mqtt_handle->js_cb_ref[MQTT_JSCALLBACK_CLIENT_STOP_REF] = js_cb_ref;
res = mqtt_client_stop(&_mqtt_handle->mqtt_handle);
if (res < 0) {
amp_debug(MOD_STR, "mqtt client stop failed \r\n");
}
out:
/* release mqtt in mqtt_yield_task() */
g_mqtt_close_flag = 1;
aos_sem_wait(&g_mqtt_close_sem, MQTT_TASK_YIELD_TIMEOUT + 50);
g_mqtt_close_flag = 0;
return 1;
}
static void module_mqtt_source_clean(void)
{
if (g_mqtt_close_flag) {
aos_sem_wait(&g_mqtt_close_sem, MQTT_TASK_YIELD_TIMEOUT + 50);
g_mqtt_close_flag = 0;
}
}
void module_mqtt_register(void)
{
duk_context *ctx = be_get_context();
if (!g_mqtt_close_sem) {
if (aos_sem_new(&g_mqtt_close_sem, 0) != 0) {
amp_error(MOD_STR, "create mqtt sem fail \r\n");
return;
}
}
amp_module_free_register(module_mqtt_source_clean);
duk_push_object(ctx);
AMP_ADD_FUNCTION("start", native_mqtt_start, 2);
AMP_ADD_FUNCTION("subscribe", native_mqtt_subscribe, 3);
AMP_ADD_FUNCTION("unsubscribe", native_mqtt_unsubscribe, 3);
AMP_ADD_FUNCTION("publish", native_mqtt_publish, 5);
AMP_ADD_FUNCTION("close", native_mqtt_close, 2);
duk_put_prop_string(ctx, -2, "MQTT");
}
| YifuLiu/AliOS-Things | components/py_engine/modules/mqtt/module_mqtt.c | C | apache-2.0 | 10,382 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "stdint.h"
/**
* @brief subdev模块内部发生值得用户关注的状态变化时, 通知用户的事件类型
*/
typedef enum {
/**
* @brief 非法的应答报文
*/
MQTT_JSCALLBACK_INVALID_REF,
/**
* @brief 应答报文的id字段非法
*/
MQTT_JSCALLBACK_START_CLIENT_REF,
/**
* @brief 应答报文的id字段非法
*/
MQTT_JSCALLBACK_SCRIBE_TOPIC_REF,
/**
* @brief 应答报文的id字段非法
*/
MQTT_JSCALLBACK_UNSCRIBE_TOPIC_REF,
/**
* @brief 应答报文的id字段非法
*/
MQTT_JSCALLBACK_PUBLISH_REF,
/**
* @brief 应答报文的id字段非法
*/
MQTT_JSCALLBACK_CLIENT_STOP_REF,
/**
* @brief 应答报文的code字段非法
*/
MQTT_JSCALLBACK_INVALID_CODE
} amp_mqtt_jscallback_type_t;
typedef struct amp_mqtt_params {
char *host;
uint16_t port;
char *clientid;
char *username;
char *password;
uint8_t keepaliveSec;
int js_cb_ref[MQTT_JSCALLBACK_INVALID_CODE];
int res;
} amp_mqtt_params_t;
typedef struct amp_mqtt_handle {
void *mqtt_handle;
int js_cb_ref[MQTT_JSCALLBACK_INVALID_CODE];
int res;
} amp_mqtt_handle_t;
/* create mqtt client */
int32_t mqtt_client_start(void **handle, amp_mqtt_params_t *mqtt_params);
/* destroy mqtt client */
int32_t mqtt_client_stop(void **handle); | YifuLiu/AliOS-Things | components/py_engine/modules/mqtt/module_mqtt.h | C | apache-2.0 | 1,450 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "aiot_mqtt_api.h"
#include "aiot_state_api.h"
#include "aiot_sysdep_api.h"
#include "amp_platform.h"
#include "amp_task.h"
#include "aos/kv.h"
#include "aos_system.h"
#include "be_inl.h"
#include "module_mqtt.h"
#include "py_defines.h"
#define MOD_STR "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 mqtt_process_thread_running = 0;
uint8_t mqtt_recv_thread_running = 0;
/* 执行aiot_mqtt_process的线程, 包含心跳发送和QoS1消息重发 */
void mqtt_process_thread(void *args)
{
int32_t res = STATE_SUCCESS;
while (mqtt_process_thread_running) {
res = aiot_mqtt_process(args);
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
aos_task_exit(0);
return;
}
/* 执行aiot_mqtt_recv的线程, 包含网络自动重连和从服务器收取MQTT消息 */
void mqtt_recv_thread(void *args)
{
int32_t res = STATE_SUCCESS;
while (mqtt_recv_thread_running) {
res = aiot_mqtt_recv(args);
if (res < STATE_SUCCESS) {
if (res == STATE_USER_INPUT_EXEC_DISABLED) {
break;
}
aos_msleep(1000);
}
}
aos_task_exit(0);
return;
}
/* MQTT默认消息处理回调, 当SDK从服务器收到MQTT消息时,
* 且无对应用户回调处理时被调用 */
void mqtt_recv_handler(void *handle, const aiot_mqtt_recv_t *packet,
void *userdata)
{
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\r\n",
-packet->data.sub_ack.res, packet->data.sub_ack.packet_id,
packet->data.sub_ack.max_qos);
/* TODO: 处理服务器对订阅请求的回应, 一般不处理 */
}
break;
case AIOT_MQTTRECV_PUB:
{
amp_debug(MOD_STR, "pub, qos: %d, topic: %.*s\r\n",
packet->data.pub.qos, packet->data.pub.topic_len,
packet->data.pub.topic);
amp_debug(MOD_STR, "pub, payload: %.*s \r\n",
packet->data.pub.payload_len, packet->data.pub.payload);
/* TODO: 处理服务器下发的业务报文 */
}
break;
case AIOT_MQTTRECV_PUB_ACK:
{
amp_debug(MOD_STR, "puback, packet id: %d \r\n",
packet->data.pub_ack.packet_id);
/* TODO: 处理服务器对QoS1上报消息的回应, 一般不处理 */
}
break;
default:
{
}
}
}
/* MQTT事件回调函数, 当网络连接/重连/断开时被触发,
* 事件定义见core/aiot_mqtt_api.h */
void mqtt_event_handler(void *handle, const aiot_mqtt_event_t *event,
void *userdata)
{
switch (event->type) {
/* SDK因为用户调用了aiot_mqtt_connect()接口, 与mqtt服务器建立连接已成功
*/
case AIOT_MQTTEVT_CONNECT:
{
amp_debug(MOD_STR, "AIOT_MQTTEVT_CONNECT \r\n");
/* TODO: 处理SDK建连成功, 不可以在这里调用耗时较长的阻塞函数 */
int js_cb_ref = (int *)userdata;
amp_debug(MOD_STR, "cb ref is: %d \r\n", js_cb_ref);
duk_context *ctx = be_get_context();
be_push_ref(ctx, js_cb_ref);
duk_push_int(ctx, 9);
if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
duk_gc(ctx, 0);
}
break;
/* SDK因为网络状况被动断连后, 自动发起重连已成功 */
case AIOT_MQTTEVT_RECONNECT:
{
amp_debug(MOD_STR, "AIOT_MQTTEVT_RECONNECT \r\n");
/* TODO: 处理SDK重连成功, 不可以在这里调用耗时较长的阻塞函数 */
}
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被动断连, 不可以在这里调用耗时较长的阻塞函数 */
}
break;
default:
{
}
}
}
int32_t mqtt_client_start(void **handle, amp_mqtt_params_t *mqtt_params)
{
int32_t res = STATE_SUCCESS;
void *mqtt_handle = NULL;
char *host = mqtt_params->host;
uint16_t port = mqtt_params->port;
char *clientid = mqtt_params->clientid;
char *username = mqtt_params->username;
char *password = mqtt_params->password;
uint16_t keepaliveSec = mqtt_params->keepaliveSec;
int js_cb_ref = mqtt_params->js_cb_ref;
aiot_sysdep_network_cred_t cred;
/* 配置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 NULL;
}
/* TODO: 如果以下代码不被注释, 则例程会用TCP而不是TLS连接云平台 */
{
memset(&cred, 0, sizeof(aiot_sysdep_network_cred_t));
cred.option = AIOT_SYSDEP_NETWORK_CRED_NONE;
}
/* 配置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_CLIENTID, (void *)clientid);
/* 配置设备deviceName */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_USERNAME, (void *)username);
/* 配置设备deviceSecret */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_PASSWORD, (void *)password);
/* 配置网络连接的安全凭据, 上面已经创建好了 */
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, js_cb_ref);
/* 配置MQTT默认消息接收回调函数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_RECV_HANDLER,
(void *)mqtt_recv_handler);
/* 配置MQTT事件回调函数 */
aiot_mqtt_setopt(mqtt_handle, AIOT_MQTTOPT_EVENT_HANDLER,
(void *)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 NULL;
}
/* 创建一个单独的线程, 专用于执行aiot_mqtt_process, 它会自动发送心跳保活,
* 以及重发QoS1的未应答报文 */
mqtt_process_thread_running = 1;
aos_task_t mqtt_process_task;
if (aos_task_new_ext(&mqtt_process_task, "mqtt_process",
mqtt_process_thread, mqtt_handle, 1024 * 4,
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 NULL;
}
amp_debug(MOD_STR, "app mqtt process start \r\n");
/* 创建一个单独的线程用于执行aiot_mqtt_recv,
* 它会循环收取服务器下发的MQTT消息, 并在断线时自动重连 */
mqtt_recv_thread_running = 1;
aos_task_t mqtt_rec_task;
if (aos_task_new_ext(&mqtt_rec_task, "mqtt_rec", 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 NULL;
}
amp_debug(MOD_STR, "app mqtt rec start \r\n");
*handle = mqtt_handle;
return res;
}
/* mqtt stop */
int32_t mqtt_client_stop(void **handle)
{
int32_t res = STATE_SUCCESS;
void *mqtt_handle = NULL;
mqtt_handle = *handle;
mqtt_process_thread_running = 0;
mqtt_recv_thread_running = 0;
/* 断开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/mqtt/module_mqtt_client.c | C | apache-2.0 | 10,356 |
#include "MQTTClient.h"
#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"
#include "ulog/ulog.h"
#define LOG_TAG "MQTT_CLIENT"
#define REQ_BUF_SIZE 2048
// static char mqtt_req_buf[REQ_BUF_SIZE];
// /* @brief http response buffer */
#define RSP_BUF_SIZE 2048
// static char mqtt_rsp_buf[RSP_BUF_SIZE];
static char mqtt_buf[RSP_BUF_SIZE];
static char mqtt_readbuf[RSP_BUF_SIZE];
unsigned int mqtt_msgid = 0;
extern const mp_obj_type_t mqtt_client_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
Network n;
MQTTClient c;
MQTTPacket_connectData data;
char *ModuleName;
} mqtt_client_obj_t;
static mp_obj_t global_mqtt_on_subcribe;
void messageArrived(MessageData *md)
{
MQTTMessage *message = md->message;
LOGD(LOG_TAG, "%.*s\n", md->topicName->lenstring.len,
md->topicName->lenstring.data);
LOGD(LOG_TAG, "%.*s\n", (int)message->payloadlen, (char *)message->payload);
if (mp_obj_is_fun(global_mqtt_on_subcribe)) {
mp_call_function_2(
global_mqtt_on_subcribe,
mp_obj_new_str(md->topicName->lenstring.data,
md->topicName->lenstring.len),
mp_obj_new_str((char *)message->payload, (int)message->payloadlen));
}
}
void mqtt_client_print(const mp_print_t *print, mp_obj_t self_in,
mp_print_kind_t kind)
{
LOGD(LOG_TAG, "entern %s;\n", __func__);
mqtt_client_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "ModuleName(%s)", self->ModuleName);
}
STATIC mp_obj_t mqtt_client_new(const mp_obj_type_t *type, size_t n_args,
size_t n_kw, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s,n_args is %d ;\r\n", __func__, n_args);
char clientId[150] = { 0 };
char username[65] = { 0 };
char password[65] = { 0 };
mqtt_client_obj_t *mqtt_client_obj = m_new_obj(mqtt_client_obj_t);
if (!mqtt_client_obj) {
mp_raise_OSError(MP_EINVAL);
}
mqtt_client_obj->Base.type = &mqtt_client_type;
mqtt_client_obj->ModuleName = "client";
Network n = { 0 };
MQTTClient c = { 0 };
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.willFlag = 0;
data.MQTTVersion = 3;
if (n_args >= 1) {
char *cus_client_id = (char *)mp_obj_str_get_str(args[0]);
LOGD(LOG_TAG, "custom client id is %s\r\n", cus_client_id);
data.clientID.cstring = cus_client_id;
} else {
data.clientID.cstring = clientId;
}
data.username.cstring = username;
data.password.cstring = password;
data.keepAliveInterval = 60;
data.cleansession = 1;
mqtt_client_obj->n = n;
mqtt_client_obj->c = c;
mqtt_client_obj->data = data;
return MP_OBJ_FROM_PTR(mqtt_client_obj);
}
STATIC mp_obj_t mqtt_connect(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int rc = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mqtt_client_obj_t *mqtt_client_obj = (mqtt_client_obj_t *)self;
if (mqtt_client_obj == NULL) {
LOGE(LOG_TAG, "mqtt_client_obj is NULL\n");
return mp_const_none;
}
char *host = (char *)mp_obj_str_get_str(args[1]);
short port = mp_obj_get_int(args[2]);
int interval = mp_obj_get_int(args[3]);
mqtt_client_obj->data.keepAliveInterval = interval;
NetworkInit(&mqtt_client_obj->n);
rc = NetworkConnect(&mqtt_client_obj->n, host, port);
if (rc != 0) {
LOGD(LOG_TAG, "Network Connect failed:%d\n", rc);
return;
} else {
LOGD(LOG_TAG, "Network Connect Success!\n");
}
/* init mqtt client */
MQTTClientInit(&mqtt_client_obj->c, &mqtt_client_obj->n, 1000, mqtt_buf,
sizeof(mqtt_buf), mqtt_readbuf, sizeof(mqtt_readbuf));
/* set the default message handler */
mqtt_client_obj->c.defaultMessageHandler = messageArrived;
LOGD(LOG_TAG, "client id is %s \r\n", mqtt_client_obj->data.clientID);
LOGD(LOG_TAG, "host is %s \r\n", host);
LOGD(LOG_TAG, "port is %d \r\n", port);
/* set mqtt connect parameter */
rc = MQTTConnect(&mqtt_client_obj->c, &mqtt_client_obj->data);
if (rc != 0) {
LOGD(LOG_TAG, "MQTT Connect server failed:%d\n", rc);
} else {
LOGD(LOG_TAG, "MQTT Connect Success!\n");
}
return mp_obj_new_int(rc);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mqtt_client_connect, 4, mqtt_connect);
STATIC mp_obj_t mqtt_subscribe(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int rc = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mqtt_client_obj_t *mqtt_client_obj = (mqtt_client_obj_t *)self;
if (mqtt_client_obj == NULL) {
LOGE(LOG_TAG, "mqtt_client_obj is NULL\n");
return mp_const_none;
}
char *subtopic = (char *)mp_obj_str_get_str(args[1]);
int qos = mp_obj_get_int(args[2]);
rc = MQTTSubscribe(&mqtt_client_obj->c, subtopic, qos, messageArrived);
return mp_obj_new_int(rc);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mqtt_client_subscribe, 3, mqtt_subscribe);
STATIC mp_obj_t mqtt_username_pw_set(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int rc = -1;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mqtt_client_obj_t *mqtt_client_obj = (mqtt_client_obj_t *)self;
if (mqtt_client_obj == NULL) {
LOGE(LOG_TAG, "mqtt_client_obj is NULL\n");
return mp_const_none;
}
char *username = (char *)mp_obj_str_get_str(args[1]);
char *pwd = (char *)mp_obj_str_get_str(args[2]);
mqtt_client_obj->data.username.cstring = username;
mqtt_client_obj->data.password.cstring = pwd;
LOGD(LOG_TAG, "username is %s , pwd is %s \r\n", username, pwd);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mqtt_client_username_pw_set, 3,
mqtt_username_pw_set);
STATIC mp_obj_t mqtt_publish(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int rc = -1;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mqtt_client_obj_t *mqtt_client_obj = (mqtt_client_obj_t *)self;
if (mqtt_client_obj == NULL) {
LOGE(LOG_TAG, "mqtt_client_obj is NULL\n");
return mp_const_none;
}
char *topic = (char *)mp_obj_str_get_str(args[1]);
char *payload = (char *)mp_obj_str_get_str(args[2]);
int qos = mp_obj_get_int(args[3]);
MQTTMessage msg = { 0 };
msg.qos = qos;
msg.payload = payload;
msg.payloadlen = strlen(payload);
msg.id = ++mqtt_msgid;
rc = MQTTPublish(&mqtt_client_obj->c, topic, &msg);
return mp_obj_new_int(rc);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mqtt_client_publish, 4, mqtt_publish);
STATIC mp_obj_t mqtt_loop(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mqtt_client_obj_t *mqtt_client_obj = (mqtt_client_obj_t *)self;
if (mqtt_client_obj == NULL) {
LOGE(LOG_TAG, "mqtt_client_obj is NULL\n");
return mp_const_none;
}
if (n_args < 2) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_const_none;
}
int timeout = mp_obj_get_int(args[1]);
MQTTYield(&mqtt_client_obj->c, timeout);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mqtt_client_loop, 2, mqtt_loop);
STATIC mp_obj_t mqtt_disconnect(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mqtt_client_obj_t *mqtt_client_obj = (mqtt_client_obj_t *)self;
if (mqtt_client_obj == NULL) {
LOGE(LOG_TAG, "mqtt_client_obj is NULL\n");
return mp_const_none;
}
MQTTDisconnect(&mqtt_client_obj->c);
NetworkDisconnect(&mqtt_client_obj->n);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mqtt_client_disconnect, 1, mqtt_disconnect);
STATIC mp_obj_t mqtt_on_subcribe(mp_obj_t id, mp_obj_t func)
{
global_mqtt_on_subcribe = func;
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(mqtt_client_on_subcribe, mqtt_on_subcribe);
STATIC const mp_rom_map_elem_t mqtt_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_http) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_on_subcribe),
MP_ROM_PTR(&mqtt_client_on_subcribe) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_username_pw_set),
MP_ROM_PTR(&mqtt_client_username_pw_set) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_connect), MP_ROM_PTR(&mqtt_client_connect) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_publish), MP_ROM_PTR(&mqtt_client_publish) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_subscribe), MP_ROM_PTR(&mqtt_client_subscribe) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_loop), MP_ROM_PTR(&mqtt_client_loop) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_disconnect),
MP_ROM_PTR(&mqtt_client_disconnect) },
};
STATIC MP_DEFINE_CONST_DICT(mqtt_module_globals, mqtt_module_globals_table);
const mp_obj_type_t mqtt_client_type = {
.base = { &mp_type_type },
.name = MP_QSTR_client,
.print = mqtt_client_print,
.make_new = mqtt_client_new,
.locals_dict = (mp_obj_dict_t *)&mqtt_module_globals,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/mqtt/mqttclient.c | C | apache-2.0 | 10,351 |
#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"
#include "py/stackctrl.h"
#include "ulog/ulog.h"
#if MICROPY_PY_BLECFG
#define LOG_TAG "bleNetconfig"
typedef enum {
BLECFG_WIFIINFO = 0x1,
BLECFG_DEVINFO = 0x2,
} blecfg_info_params_t;
STATIC mp_obj_t ble_init(void)
{
mp_int_t ret = BleCfg_run();
return MP_OBJ_NEW_SMALL_INT(ret);
}
MP_DEFINE_CONST_FUN_OBJ_0(ble_init_obj, ble_init);
// STATIC mp_obj_t ble_recovery_wifi(void)
// {
// mp_int_t ret = BleCfg_recovery_wifi();
// return MP_OBJ_NEW_SMALL_INT(ret);
// }
// MP_DEFINE_CONST_FUN_OBJ_0(ble_recovery_wifi_obj, ble_recovery_wifi);
// STATIC mp_obj_t ble_recovery_devinfo(void)
// {
// mp_int_t ret = BleCfg_recovery_devinfo();
// return MP_OBJ_NEW_SMALL_INT(ret);
// }
// MP_DEFINE_CONST_FUN_OBJ_0(ble_recovery_devinfo_obj, ble_recovery_devinfo);
// mp_int_t ble_config_get_wifi_info(amp_wifi_info_t *wifi_info)
// {
// netmgr_config_t config = { 0 };
// netmgr_ifconfig_info_t info = { 0 };
// mp_int_t ap_num;
// mp_int_t used_ap; /**< ap that is used in the array */
// netmgr_hdl_t hdl = netmgr_get_dev(WIFI_DEV_PATH);
// if (hdl == -1) {
// LOGE(LOG_TAG, "get wifi info failed!, netmgr_hdl_t = %d", hdl);
// return BLE_ERR_NET_DEV;
// }
// memset(&info, 0, sizeof(info));
// if (netmgr_get_ifconfig(hdl, &info) == -1) {
// return BLE_ERR_NET_IFCONFIG;
// }
// memset(&config, 0, sizeof(config));
// if (netmgr_get_config(hdl, &config) == -1) {
// return BLE_ERR_NET_CONFIG;
// }
// ap_num = config.config.wifi_config.ap_num;
// used_ap = config.config.wifi_config.used_ap;
// if ((ap_num < MAX_AP_CONFIG_NUM) && (used_ap < ap_num)) {
// memset(wifi_info->ssid, 0, sizeof(wifi_info->ssid));
// strncpy(wifi_info->ssid, config.config.wifi_config.config[used_ap].ssid, sizeof(wifi_info->ssid) - 1);
// } else {
// return BLE_ERROR_NET_AP_CNT_INVALID;
// }
// snprintf(wifi_info->ip, sizeof(wifi_info->ip), "%s", info.ip_addr);
// memcpy(wifi_info->mac, info.mac, sizeof(wifi_info->mac));
// wifi_info->rssi = info.rssi;
// return BLE_ERR_NONE;
// }
// STATIC mp_obj_t ble_info(void)
// {
// amp_wifi_info_t wifi_info = { 0 };
// mp_int_t ret = ble_config_get_wifi_info(&wifi_info);
// if (ret != BLE_ERR_NONE) {
// LOGE(LOG_TAG, "Failed to get wifi info, ret = %d", ret);
// }
// mp_obj_t dict = mp_obj_new_dict(4);
// mp_obj_dict_store(MP_OBJ_FROM_PTR(dict), mp_obj_new_str("SSID", 4),
// mp_obj_new_str(wifi_info.ssid, strlen(wifi_info.ssid)));
// mp_obj_dict_store(MP_OBJ_FROM_PTR(dict), mp_obj_new_str("MAC", 3), mp_obj_new_str(wifi_info.mac, 6));
// mp_obj_dict_store(MP_OBJ_FROM_PTR(dict), mp_obj_new_str("IP", 2),
// mp_obj_new_str(wifi_info.ip, strlen(wifi_info.ip)));
// mp_obj_dict_store(MP_OBJ_FROM_PTR(dict), mp_obj_new_str("RSSI", 4), mp_obj_new_int(wifi_info.rssi));
// return dict;
// }
// MP_DEFINE_CONST_FUN_OBJ_0(ble_info_obj, ble_info);
// STATIC mp_obj_t ble_status(void)
// {
// netmgr_hdl_t hdl = netmgr_get_dev(WIFI_DEV_PATH);
// if (hdl == -1) {
// LOGE(LOG_TAG, "get wifi info failed!, netmgr_hdl_t = %d", hdl);
// return MP_OBJ_NEW_SMALL_INT(BLE_ERR_NET_DEV);
// }
// mp_int_t ret = netmgr_get_state(hdl);
// return MP_OBJ_NEW_SMALL_INT(ret);
// }
// MP_DEFINE_CONST_FUN_OBJ_0(ble_status_obj, ble_status);
STATIC mp_obj_t blecfg_restore(size_t n_args, const mp_obj_t *args)
{
mp_int_t ret = -1;
uint32_t params = (uint32_t)mp_obj_get_int(args[0]);
if (BLECFG_WIFIINFO == params) {
ret = BleCfg_recovery_wifi();
} else if (BLECFG_DEVINFO == params) {
ret = BleCfg_recovery_devinfo();
} else {
LOGE(LOG_TAG, "error, recovery params abnormal!\n");
}
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(blecfg_restore_obj, 1, blecfg_restore);
STATIC mp_obj_t blecfg_get(size_t n_args, const mp_obj_t *args)
{
mp_int_t ret = 0;
// wait C interface finish
return MP_OBJ_NEW_SMALL_INT(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(blecfg_get_obj, 1, blecfg_get);
STATIC mp_obj_t blecfg_clear(void)
{
mp_int_t ret = 0;
// wait C interface finish
return MP_OBJ_NEW_SMALL_INT(ret);
}
MP_DEFINE_CONST_FUN_OBJ_0(blecfg_clear_obj, blecfg_clear);
STATIC const mp_rom_map_elem_t blecfg_module_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_blecfg) },
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&ble_init_obj) },
// { MP_ROM_QSTR(MP_QSTR_recovery_wifi), MP_ROM_PTR(&ble_recovery_wifi_obj) },
// { MP_ROM_QSTR(MP_QSTR_recovery_devinfo), MP_ROM_PTR(&ble_recovery_devinfo_obj) },
// { MP_ROM_QSTR(MP_QSTR_info), MP_ROM_PTR(&ble_info_obj) },
// { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&ble_status_obj) },
{ MP_ROM_QSTR(MP_QSTR_restore), MP_ROM_PTR(&blecfg_restore_obj) },
{ MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&blecfg_get_obj) },
{ MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&blecfg_clear_obj) },
{ MP_ROM_QSTR(MP_QSTR_WifiInfo), MP_ROM_INT(BLECFG_WIFIINFO) },
{ MP_ROM_QSTR(MP_QSTR_DevInfo), MP_ROM_INT(BLECFG_DEVINFO) },
};
STATIC MP_DEFINE_CONST_DICT(blecfg_module_globals, blecfg_module_globals_table);
const mp_obj_module_t mp_module_blecfg = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&blecfg_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_blecfg, mp_module_blecfg, MICROPY_PY_BLECFG);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/netconfig/blecfg.c | C | apache-2.0 | 5,682 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aos_network.h"
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "aos_log.h"
#include "utility.h"
#include "aos/kernel.h"
#define LOG_TAG "mod_netmgr"
STATIC aos_wifi_manager_t *wifi_manager = NULL;
static mp_obj_t on_wifi_event_cb = mp_const_none;
static void wifi_event_cb(uint32_t event_id, void *context)
{
if (on_wifi_event_cb != mp_const_none && mp_obj_is_callable(on_wifi_event_cb)) {
callback_to_python_LoBo(on_wifi_event_cb, MP_OBJ_NEW_SMALL_INT(event_id), NULL);
}
}
STATIC mp_obj_t wifi_init()
{
if (!wifi_manager) {
wifi_manager = calloc(sizeof(aos_wifi_manager_t), 1);
if (!wifi_manager) {
return MP_ROM_INT(-MP_ENOMEM);
}
wifi_manager->cb = wifi_event_cb;
wifi_manager->wifi_state = AOS_NET_NOINIT;
// wifi_manager->wifi_mode = self->if_mode;
wifi_manager->wifi_mode = AOS_NETWORK_WIFI_STA;
wifi_manager->is_initialized = false;
wifi_manager->is_started = false;
pthread_mutex_init(&wifi_manager->network_mutex, NULL);
}
pthread_mutex_lock(&wifi_manager->network_mutex);
aos_wifi_init(wifi_manager);
pthread_mutex_unlock(&wifi_manager->network_mutex);
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_wifi_init_obj, wifi_init);
STATIC mp_obj_t wifi_active()
{
return MP_ROM_INT(aos_wifi_start(wifi_manager));
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_wifi_active_obj, wifi_active);
STATIC mp_obj_t wifi_deactive()
{
return MP_ROM_INT(aos_wifi_stop(wifi_manager));
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_wifi_deactive_obj, wifi_deactive);
STATIC mp_obj_t wifi_deinit()
{
if (wifi_manager) {
aos_wifi_deinit(wifi_manager);
wifi_manager->cb = NULL;
free(wifi_manager);
wifi_manager = NULL;
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_wifi_deinit_obj, wifi_deinit);
STATIC mp_obj_t wifi_connect(mp_obj_t ssid_in, mp_obj_t pwd_in)
{
const char *_ssid = mp_obj_str_get_str(ssid_in);
const char *_pwd = mp_obj_str_get_str(pwd_in);
if (!wifi_manager->wifi_state == AOS_NET_STA_CONNECTED) {
return mp_const_none;
}
if (!wifi_manager) {
wifi_init();
}
pthread_mutex_lock(&wifi_manager->network_mutex);
if (!wifi_manager->wifi_state == AOS_NET_STA_CONNECTED) {
pthread_mutex_unlock(&wifi_manager->network_mutex);
return mp_const_none;
}
MP_THREAD_GIL_EXIT();
aos_wifi_connect(_ssid, _pwd);
pthread_mutex_unlock(&wifi_manager->network_mutex);
MP_THREAD_GIL_ENTER();
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(netmgr_wifi_connect_obj, wifi_connect);
STATIC mp_obj_t wifi_disconnect()
{
if (wifi_manager != NULL) {
pthread_mutex_lock(&wifi_manager->network_mutex);
aos_wifi_disconnect();
pthread_mutex_unlock(&wifi_manager->network_mutex);
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_wifi_disconnect_obj, wifi_disconnect);
STATIC mp_obj_t wifi_get_status()
{
if (wifi_manager != NULL)
return mp_obj_new_int(wifi_manager->wifi_state);
else {
return mp_obj_new_int(-1);
}
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_wifi_get_status_obj, wifi_get_status);
STATIC mp_obj_t wifi_on(mp_obj_t func)
{
on_wifi_event_cb = func;
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_1(netmgr_wifi_on_obj, wifi_on);
STATIC mp_obj_t wifi_get_info()
{
aos_wifi_info_t wifi_info = { 0 };
mp_int_t ret = aos_wifi_get_info(&wifi_info);
if (ret < 0) {
AOS_LOGE(LOG_TAG, "Failed to get wifi info\r\n");
return mp_const_none;
}
mp_obj_t dict = mp_obj_new_dict(4);
mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(qstr_from_str("ssid")), mp_obj_new_strn(wifi_info.ssid));
mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(qstr_from_str("mac")), mp_obj_new_strn(wifi_info.mac));
mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(qstr_from_str("ip")), mp_obj_new_strn(wifi_info.ip));
mp_obj_dict_store(dict, MP_OBJ_NEW_QSTR(qstr_from_str("rssi")), mp_obj_new_int(wifi_info.rssi));
return dict;
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_wifi_get_info_obj, wifi_get_info);
STATIC mp_obj_t aos_ifconfig(mp_obj_t config_in)
{
aos_ifconfig_info_t info = { 0 };
info.dhcp_en = get_int_from_dict(config_in, "dhcp_en") == 0 ? false : true;
const char *ip_addr = get_str_from_dict(config_in, "ip_addr");
if (ip_addr == NULL) {
return mp_obj_new_int(-1);
} else {
memcpy(info.ip_addr, ip_addr, strlen(ip_addr));
}
const char *mask = get_str_from_dict(config_in, "mask");
if (mask == NULL) {
return mp_obj_new_int(-1);
} else {
memcpy(info.mask, mask, strlen(mask));
}
const char *gw = get_str_from_dict(config_in, "gw");
if (gw == NULL) {
return mp_obj_new_int(-1);
} else {
memcpy(info.gw, gw, strlen(gw));
}
const char *dns_server = get_str_from_dict(config_in, "dns_server");
if (dns_server == NULL) {
return mp_obj_new_int(-1);
} else {
memcpy(info.dns_server, dns_server, strlen(dns_server));
}
const char *mac = get_str_from_dict(config_in, "mac");
if (mac == NULL) {
return mp_obj_new_int(-1);
} else {
memcpy(info.mac, mac, strlen(mac));
}
info.rssi = get_int_from_dict(config_in, "rssi");
mp_int_t ret = aos_net_set_ifconfig(&info);
return mp_obj_new_int(ret);
}
MP_DEFINE_CONST_FUN_OBJ_1(netmgr_ifconfig_obj, aos_ifconfig);
STATIC mp_obj_t aos_get_ifconfig()
{
aos_ifconfig_info_t info = { 0 };
mp_int_t ret = aos_net_get_ifconfig(&info);
if (ret != 0) {
AOS_LOGI(LOG_TAG, "netmgr_get_config failed, ret = %d\r\n", ret);
return mp_const_none;
}
mp_obj_t config_dict = mp_obj_new_dict(6);
mp_obj_dict_store(config_dict, MP_OBJ_NEW_QSTR(qstr_from_str("ip_addr")), mp_obj_new_strn(info.ip_addr));
mp_obj_dict_store(config_dict, MP_OBJ_NEW_QSTR(qstr_from_str("mask")), mp_obj_new_strn(info.mask));
mp_obj_dict_store(config_dict, MP_OBJ_NEW_QSTR(qstr_from_str("gateway")), mp_obj_new_strn(info.gw));
mp_obj_dict_store(config_dict, MP_OBJ_NEW_QSTR(qstr_from_str("dns")), mp_obj_new_strn(info.dns_server));
mp_obj_dict_store(config_dict, MP_OBJ_NEW_QSTR(qstr_from_str("mac")), mp_obj_new_strn(info.mac));
mp_obj_dict_store(config_dict, MP_OBJ_NEW_QSTR(qstr_from_str("rssi")), mp_obj_new_int(info.rssi));
return config_dict;
}
MP_DEFINE_CONST_FUN_OBJ_0(netmgr_get_ifconfig_obj, aos_get_ifconfig);
STATIC const mp_rom_map_elem_t netmgr_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_netmgr) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_init), MP_ROM_PTR(&netmgr_wifi_init_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&netmgr_wifi_deinit_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_connect), MP_ROM_PTR(&netmgr_wifi_connect_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&netmgr_wifi_disconnect_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getStatus), MP_ROM_PTR(&netmgr_wifi_get_status_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_on), MP_ROM_PTR(&netmgr_wifi_on_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getInfo), MP_ROM_PTR(&netmgr_wifi_get_info_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&netmgr_ifconfig_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getIfconfig), MP_ROM_PTR(&netmgr_get_ifconfig_obj) },
/* network connect state */
{ MP_ROM_QSTR(MP_QSTR_NET_AP_DISCONNECTING), MP_ROM_INT(AOS_NET_STA_LOST_IP) },
{ MP_ROM_QSTR(MP_QSTR_NET_AP_DISCONNECTED), MP_ROM_INT(AOS_NET_STA_DISCONNECTED) },
{ MP_ROM_QSTR(MP_QSTR_NET_AP_CONNECTING), MP_ROM_INT(AOS_NET_STA_GOT_IP) },
{ MP_ROM_QSTR(MP_QSTR_NET_AP_CONNECTED), MP_ROM_INT(AOS_NET_STA_CONNECTED) },
{ MP_ROM_QSTR(MP_QSTR_NET_IP_OBTAINING), MP_ROM_INT(AOS_NET_STA_GOT_IP) },
{ MP_ROM_QSTR(MP_QSTR_NET_IP_OBTAINED), MP_ROM_INT(AOS_NET_STA_GOT_IP) },
{ MP_ROM_QSTR(MP_QSTR_NET_FAILED), MP_ROM_INT(AOS_NET_STA_DISCONNECTED) },
/* network type */
{ MP_ROM_QSTR(MP_QSTR_NET_TYPE_WIFI), MP_ROM_INT(AOS_NETWORK_WIFI) },
{ MP_ROM_QSTR(MP_QSTR_NET_TYPE_CELLULAR), MP_ROM_INT(AOS_NETWORK_CELLULAR) },
{ MP_ROM_QSTR(MP_QSTR_NET_TYPE_ETH), MP_ROM_INT(AOS_NETWORK_ETHERNET) },
};
STATIC MP_DEFINE_CONST_DICT(hapy_netmgr_module_globals, netmgr_module_globals_table);
const mp_obj_module_t netmgr_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&hapy_netmgr_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_netmgr, netmgr_module, MICROPY_PY_NETMGR);
| YifuLiu/AliOS-Things | components/py_engine/modules/netmgr/modnetmgr.c | C | apache-2.0 | 8,682 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <stdarg.h>
#include <string.h>
#include "aos_network.h"
#include "aos_system.h"
#include "be_inl.h"
#include "board_config.h"
#define MOD_STR "CELLULAR"
typedef struct {
int status;
int js_cb_ref;
} network_status_notify_param_t;
static int g_js_cb_ref = 0;
/*************************************************************************************
* 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 duk_ret_t native_cellular_get_simInfo(duk_context *ctx)
{
int ret = -1;
amp_sim_info_t sim_info;
memset(&sim_info, 0, sizeof(sim_info));
ret = amp_get_sim_info(&sim_info);
if (ret != 0) {
amp_debug(MOD_STR, "get sim card info failed");
goto out;
}
duk_push_object(ctx);
AMP_ADD_STRING("imsi", sim_info.imsi);
AMP_ADD_STRING("imei", sim_info.imei);
AMP_ADD_STRING("iccid", sim_info.iccid);
return 1;
out:
duk_push_int(ctx, ret);
return 1;
}
/*************************************************************************************
* 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 duk_ret_t native_cellular_get_locatorInfo(duk_context *ctx)
{
int ret = -1;
amp_locator_info_t locator_info;
memset(&locator_info, 0, sizeof(locator_info));
ret = amp_get_locator_info(&locator_info);
if (ret != 0) {
amp_debug(MOD_STR, "get locator card info failed");
goto out;
}
duk_push_object(ctx);
AMP_ADD_INT("cellid", locator_info.cellid);
AMP_ADD_INT("lac", locator_info.lac);
AMP_ADD_STRING("mcc", locator_info.mcc);
AMP_ADD_STRING("mnc", locator_info.mnc);
AMP_ADD_INT("signal", locator_info.signal);
return 1;
out:
duk_push_int(ctx, ret);
return 1;
}
/*************************************************************************************
* 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
**************************************************************************************/
void cellInfo_receive_callback(amp_locator_info_t *locator_info, int cell_num)
{
int ret = -1;
int i;
duk_context *ctx = be_get_context();
be_push_ref(ctx, g_js_cb_ref);
int arr_idx = duk_push_array(ctx);
for (i = 0; i < cell_num; i++) {
duk_push_object(ctx);
AMP_ADD_INT("cellid", locator_info[i].cellid);
AMP_ADD_INT("lac", locator_info[i].lac);
AMP_ADD_STRING("mcc", locator_info[i].mcc);
AMP_ADD_STRING("mnc", locator_info[i].mnc);
duk_put_prop_index(ctx, arr_idx, i);
}
if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
}
static duk_ret_t native_cellular_neighborCellInfo(duk_context *ctx)
{
int ret = -1;
// int i,cellnum = 0;
// if (!duk_is_function(ctx, 0)) {
// amp_warn(MOD_STR, "parameter must be function");
// goto out;
// }
// duk_dup(ctx, 1);
// g_js_cb_ref = be_ref(ctx);
ret = amp_get_neighbor_locator_info(cellInfo_receive_callback);
if (ret != 0) {
amp_debug(MOD_STR, "get locator card info failed");
goto out;
}
return 1;
out:
duk_push_int(ctx, ret);
return 1;
}
static duk_ret_t native_cellular_getStatus(duk_context *ctx)
{
int ret = -1;
ret = aos_get_network_status();
if (ret != 1) {
amp_debug(MOD_STR, "network status disconnect %d", ret);
goto out;
}
out:
duk_push_int(ctx, ret);
return 1;
}
static void network_status_notify(void *pdata)
{
int i = 0;
network_status_notify_param_t *p = (network_status_notify_param_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx, p->js_cb_ref);
duk_push_int(ctx, p->status);
if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
aos_free(p);
duk_pop(ctx);
duk_gc(ctx, 0);
}
static void network_status_callback(int status, void *args)
{
int js_cb_ref = (int)args;
network_status_notify_param_t *p =
aos_calloc(1, sizeof(network_status_notify_param_t));
if (!p) {
amp_warn(MOD_STR, "allocate memory failed");
duk_context *ctx = be_get_context();
be_unref(ctx, js_cb_ref);
return;
}
p->status = status;
p->js_cb_ref = js_cb_ref;
py_task_schedule_call(network_status_notify, p);
}
static duk_ret_t native_cellular_onconnect(duk_context *ctx)
{
int ret = -1;
int js_cb_ref;
if (!duk_is_function(ctx, 0)) {
amp_warn(MOD_STR, "parameter must be function");
goto out;
}
duk_dup(ctx, 0);
js_cb_ref = be_ref(ctx);
ret = aos_network_status_registercb(network_status_callback, js_cb_ref);
if (ret != 0) {
duk_context *ctx = be_get_context();
be_unref(ctx, js_cb_ref);
return -1;
}
out:
duk_push_int(ctx, ret);
return 1;
}
static duk_ret_t native_get_netshare_mode(duk_context *ctx)
{
int ret = -1;
ret = amp_get_netsharemode();
out:
duk_push_int(ctx, ret);
return 1;
}
static duk_ret_t native_set_netshare_mode(duk_context *ctx)
{
int ret = -1;
int share_mode = 0;
if (!duk_is_number(ctx, 0)) {
amp_warn(MOD_STR, "parameter must be number");
goto out;
}
share_mode = duk_get_number(ctx, 0);
amp_error(MOD_STR, "native set net share mode = %d", share_mode);
ret = amp_set_netsharemode(share_mode);
if (ret != 0) {
return -1;
}
amp_error(MOD_STR, "native set net share mode success");
out:
duk_push_int(ctx, ret);
return 1;
}
static duk_ret_t native_get_netshare_config(duk_context *ctx)
{
int ret = -1;
amp_sharemode_info_t *share_mode_info;
share_mode_info = aos_malloc(sizeof(amp_sharemode_info_t));
if (share_mode_info == NULL) {
amp_debug(MOD_STR, "get net share config failed");
goto out;
}
memset(share_mode_info, 0, sizeof(amp_sharemode_info_t));
ret = amp_get_netshareconfig(share_mode_info);
if (ret != 0) {
amp_debug(MOD_STR, "get net share config failed");
goto out;
}
duk_push_object(ctx);
AMP_ADD_INT("action", share_mode_info->action);
AMP_ADD_INT("auto_connect", share_mode_info->auto_connect);
AMP_ADD_STRING("apn", share_mode_info->apn);
AMP_ADD_STRING("username", share_mode_info->username);
AMP_ADD_STRING("password", share_mode_info->password);
AMP_ADD_INT("ip_type", share_mode_info->ip_type);
AMP_ADD_INT("share_mode", share_mode_info->share_mode);
aos_free(share_mode_info);
return 1;
out:
if (share_mode_info) {
aos_free(share_mode_info);
}
duk_push_int(ctx, ret);
return 1;
}
static duk_ret_t native_set_netshare_config(duk_context *ctx)
{
int ret = -1;
amp_sharemode_info_t *share_mode_info;
/* check paramters */
if (!duk_is_object(ctx, 0)) {
amp_warn(MOD_STR, "parameter must be object\n");
goto out;
}
/* get device certificate */
duk_get_prop_string(ctx, 0, "ucid");
duk_get_prop_string(ctx, 0, "action");
duk_get_prop_string(ctx, 0, "autoConnect");
duk_get_prop_string(ctx, 0, "apn");
duk_get_prop_string(ctx, 0, "username");
duk_get_prop_string(ctx, 0, "password");
duk_get_prop_string(ctx, 0, "authType");
duk_get_prop_string(ctx, 0, "ipType");
// if (!duk_is_number(ctx, -8) || !duk_is_number(ctx, -7) ||
// !duk_is_number(ctx, -6) || !duk_is_string(ctx, -5) ||
// !duk_is_string(ctx, -4) || !duk_is_string(ctx, -3) ||
// !duk_is_number(ctx, -2) || !duk_is_number(ctx, -1))
// {
// amp_warn(MOD_STR,
// "Parameter 1 must be an object like {host: string, "
// "port: uint, client_id: string, username: string, "
// "password: string, keepalive_interval: uint} %d %d %d %d %d %d %d
// %d %d", duk_is_number(ctx, -8), duk_is_number(ctx, -7),
// duk_is_number(ctx, -6), duk_is_string(ctx, -5),
// duk_is_string(ctx, -4), duk_is_string(ctx, -3),
// duk_is_string(ctx, -2), duk_is_boolean(ctx, -2),
// duk_is_number(ctx, -1));
// // duk_pop_n(ctx, 8);
// // goto out;
// }
const uint16_t ipType = duk_get_number(ctx, -1);
const uint16_t authType = duk_get_number(ctx, -2);
const char *password = duk_get_string(ctx, -3);
const char *username = duk_get_string(ctx, -4);
const char *apn = duk_get_string(ctx, -5);
const uint16_t autoConnect = duk_get_number(ctx, -6);
const uint16_t action = duk_get_number(ctx, -7);
const uint16_t ucid = duk_get_number(ctx, -8);
share_mode_info = aos_malloc(sizeof(amp_sharemode_info_t));
if (share_mode_info == NULL) {
amp_debug(MOD_STR, "set net share config failed");
goto out;
}
memset(share_mode_info, 0, sizeof(amp_sharemode_info_t));
share_mode_info->action = action;
share_mode_info->auto_connect = autoConnect;
memcpy(share_mode_info->apn, apn, strlen(apn));
memcpy(share_mode_info->username, username, strlen(username));
memcpy(share_mode_info->password, password, strlen(password));
share_mode_info->ip_type = ipType;
ret = amp_set_netshareconfig(ucid, authType, share_mode_info);
if (ret != 0) {
amp_warn(MOD_STR, "amp set net share config failed!");
aos_free(share_mode_info);
return -1;
}
out:
if (share_mode_info) {
aos_free(share_mode_info);
}
duk_push_int(ctx, ret);
return 1;
}
void module_cellular_register(void)
{
duk_context *ctx = be_get_context();
duk_push_object(ctx);
AMP_ADD_FUNCTION("getSimInfo", native_cellular_get_simInfo, 0);
AMP_ADD_FUNCTION("getLocatorInfo", native_cellular_get_locatorInfo, 0);
AMP_ADD_FUNCTION("getStatus", native_cellular_getStatus, 0);
AMP_ADD_FUNCTION("onConnect", native_cellular_onconnect, 1);
AMP_ADD_FUNCTION("getNeighborCellInfo", native_cellular_neighborCellInfo,
0);
AMP_ADD_FUNCTION("getNetSharemode", native_get_netshare_mode, 0);
AMP_ADD_FUNCTION("setNetSharemode", native_set_netshare_mode, 1);
AMP_ADD_FUNCTION("getNetShareconfig", native_get_netshare_config, 0);
AMP_ADD_FUNCTION("setNetShareconfig", native_set_netshare_config, 1);
duk_put_prop_string(ctx, -2, "CELLULAR");
}
| YifuLiu/AliOS-Things | components/py_engine/modules/network/cellular/module_cellular.c | C | apache-2.0 | 11,247 |
#include "httpclient.h"
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "aos/kernel.h"
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#define LOG_TAG "HTTP_CLIENT"
#define REQ_BUF_SIZE 2048
static char req_buf[REQ_BUF_SIZE];
/* @brief http response buffer */
#define HTTP_RSP_BUF_SIZE 2048
static char rsp_buf[HTTP_RSP_BUF_SIZE];
#define HTTP_BUFF_SIZE 2048
#define HTTP_HEADER_SIZE 1024
#define HTTP_HEADER_COUNT 8
#define HTTP_REQUEST_PARAMS_LEN_MAX 2048
#define HTTP_SEND_RECV_TIMEOUT 10000
#define HTTP_REQUEST_TIMEOUT 30000
#define HTTP_DEFAULT_HEADER_NAME "content-type"
#define HTTP_DEFAULT_HEADER_DATA "application/json"
#define HTTP_CRLF "\r\n"
extern const mp_obj_type_t http_client_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 *ModuleName;
httpclient_t client;
httpclient_data_t client_data;
} http_client_obj_t;
typedef struct {
char *name;
char *data;
} http_header_t;
typedef struct {
char *url;
char *filepath;
int method;
http_header_t http_header[HTTP_HEADER_COUNT];
uint32_t timeout;
char *params;
char *buffer;
int params_len;
int js_cb_ref;
} http_param_t;
void http_client_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind)
{
LOGD(LOG_TAG, "entern %s;\n", __func__);
http_client_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "ModuleName(%s)", self->ModuleName);
}
STATIC mp_obj_t http_client_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s;\n", __func__);
http_client_obj_t *http_client_obj = m_new_obj(http_client_obj_t);
if (!http_client_obj) {
mp_raise_OSError(MP_EINVAL);
}
http_client_obj->Base.type = &http_client_type;
http_client_obj->ModuleName = "client";
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
http_client_obj->client = client;
http_client_obj->client_data = client_data;
// http_client_obj->i2c_handle.handle = NULL;
memset(req_buf, 0, sizeof(req_buf));
http_client_obj->client_data.header_buf = req_buf;
http_client_obj->client_data.header_buf_len = sizeof(req_buf);
memset(rsp_buf, 0, sizeof(rsp_buf));
http_client_obj->client_data.response_buf = rsp_buf;
http_client_obj->client_data.response_buf_len = sizeof(rsp_buf);
return MP_OBJ_FROM_PTR(http_client_obj);
}
STATIC mp_obj_t obj_http_get(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_get(&http_client_obj->client, url, &http_client_obj->client_data);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_get, 2, obj_http_get);
STATIC mp_obj_t obj_http_put(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_put(&http_client_obj->client, url, &http_client_obj->client_data);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_put, 2, obj_http_put);
STATIC mp_obj_t obj_http_post(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_post(&http_client_obj->client, url, &http_client_obj->client_data);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_post, 2, obj_http_post);
STATIC mp_obj_t http_set_header(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *header = (char *)mp_obj_str_get_str(args[1]);
http_client_obj->client.header = header;
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_set_header, 2, http_set_header);
STATIC mp_obj_t http_set_data(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ);
http_client_obj->client_data.post_buf = bufinfo.buf;
http_client_obj->client_data.post_buf_len = mp_obj_get_int(args[2]);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_set_data, 3, http_set_data);
STATIC mp_obj_t obj_http_header(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_head(&http_client_obj->client, url, &http_client_obj->client_data);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_header, 2, obj_http_header);
STATIC mp_obj_t obj_http_conn(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_conn(&http_client_obj->client, url);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_conn, 2, obj_http_conn);
STATIC mp_obj_t obj_http_recv(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_recv(&http_client_obj->client, &http_client_obj->client_data);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_recv, 1, obj_http_recv);
STATIC mp_obj_t obj_http_send(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
int method = mp_obj_get_int(args[2]);
ret = httpclient_send(&http_client_obj->client, url, method, &http_client_obj->client_data);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_send, 3, obj_http_send);
STATIC mp_obj_t obj_http_get_res_header_value(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_get_response_code(&http_client_obj->client);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_get_res_header_value, 2, obj_http_get_res_header_value);
STATIC mp_obj_t obj_http_get_res_code(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_get_response_code(&http_client_obj->client);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_get_res_code, 1, obj_http_get_res_code);
STATIC mp_obj_t obj_http_get_add_text(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
if (n_args < 6) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *content_disposition = (char *)mp_obj_str_get_str(args[1]);
char *name = (char *)mp_obj_str_get_str(args[3]);
char *content_type = (char *)mp_obj_str_get_str(args[2]);
char *data = (char *)mp_obj_str_get_str(args[4]);
int data_len = mp_obj_get_int(args[5]);
ret =
httpclient_formdata_addtext(&http_client_obj->client, content_disposition, content_type, name, data, data_len);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_add_text, 6, obj_http_get_add_text);
STATIC mp_obj_t obj_http_get_add_file(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *content_disposition = (char *)mp_obj_str_get_str(args[1]);
char *name = (char *)mp_obj_str_get_str(args[2]);
char *content_type = (char *)mp_obj_str_get_str(args[3]);
char *file_path = (char *)mp_obj_str_get_str(args[4]);
ret = httpclient_formdata_addfile(&http_client_obj->client, content_disposition, name, content_type, file_path);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_add_file, 5, obj_http_get_add_file);
STATIC mp_obj_t obj_http_delete(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = (char *)mp_obj_str_get_str(args[1]);
ret = httpclient_delete(&http_client_obj->client, url, &http_client_obj->client_data);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_delete, 2, obj_http_delete);
STATIC mp_obj_t obj_http_reset(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
httpclient_reset(&http_client_obj->client);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_reset, 1, obj_http_reset);
STATIC mp_obj_t obj_http_prepare(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
int header_size = mp_obj_get_int(args[1]);
int resp_size = mp_obj_get_int(args[2]);
ret = httpclient_prepare(&http_client_obj->client, header_size, resp_size);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_prepare, 3, obj_http_prepare);
STATIC mp_obj_t obj_http_unprepare(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
ret = httpclient_unprepare(&http_client_obj->client);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_unprapare, 1, obj_http_unprepare);
STATIC mp_obj_t obj_http_close(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
httpclient_clse(&http_client_obj->client);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_client_close, 1, obj_http_close);
STATIC mp_obj_t obj_http_get_response(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
mp_obj_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
return mp_obj_new_str(http_client_obj->client_data.response_buf, strlen(http_client_obj->client_data.response_buf));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_get_response, 1, obj_http_get_response);
static void http_request_notify(void *pdata)
{
http_param_t *msg = (http_param_t *)pdata;
}
/* create task for http download */
static bool task_http_download_func(char *url, char *filepath)
{
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
int num = 0;
int ret;
bool download_result = false;
if (!aos_access(filepath, 0)) {
aos_remove(filepath);
}
// 字符串偶现丢失,不知原因,暂时写死,by梓同
// char * req_url = param->url;
// int fd = aos_open(param->filepath, O_CREAT | O_RDWR | O_APPEND);
int fd = aos_open(filepath, O_CREAT | O_RDWR | O_APPEND);
char *req_url = url;
// printf("usr ls %s , filepath is %s \r\n",req_url,param->filepath);
memset(rsp_buf, 0, sizeof(rsp_buf));
client_data.response_buf = rsp_buf;
client_data.response_buf_len = sizeof(rsp_buf);
ret = httpclient_conn(&client, req_url);
if (!ret) {
ret = httpclient_send(&client, req_url, HTTP_GET, &client_data);
do {
ret = httpclient_recv(&client, &client_data);
// printf("response_content_len=%d,
// retrieve_len=%d,content_block_len=%d\n",
// client_data.response_content_len,client_data.retrieve_len,client_data.content_block_len);
// printf("ismore=%d\n", client_data.is_more);
if (client_data.content_block_len > 0) {
num = aos_write(fd, client_data.response_buf, client_data.content_block_len);
if (num > 0) {
printf("aos_write num=%d\n", num);
}
}
} while (client_data.is_more);
if (client_data.response_content_len == 0)
download_result = false;
else
download_result = true;
} else {
download_result = false;
}
// printf("************task_http_download_func0********** \r\n");
if (download_result) {
ret = aos_sync(fd);
} else {
aos_remove(filepath);
}
aos_close(fd);
// param->buffer = "http download success";
// printf("************task_http_download_func1********** \r\n");
httpclient_clse(&client);
// amp_task_schedule_call(http_request_notify, param);
// printf("************task_http_download_func2********** \r\n");
return download_result;
}
STATIC mp_obj_t obj_http_download(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
aos_task_t http_task;
http_param_t *http_param = NULL;
char *http_buffer = NULL;
bool result = false;
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = mp_obj_str_get_str(args[1]);
char *filepath = mp_obj_str_get_str(args[2]);
http_param = (http_param_t *)aos_malloc(sizeof(http_param_t));
if (!http_param) {
goto done;
}
memset(http_param, 0, sizeof(http_param_t));
http_param->buffer = http_buffer;
http_param->url = url;
http_param->filepath = filepath;
// aos_task_new_ext(&http_task, "amp http download task",
// task_http_download_func, http_param, 1024 * 8, AOS_DEFAULT_APP_PRI + 3);
result = task_http_download_func(url, filepath);
done:
if (http_buffer)
aos_free(http_buffer);
if (http_param && http_param->params)
cJSON_free(http_param->params);
if (http_param)
aos_free(http_param);
return result ? mp_obj_new_int(1) : mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_download, 3, obj_http_download);
STATIC mp_obj_t obj_http_request(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
aos_task_t http_task;
http_param_t *http_param = NULL;
char *http_buffer = NULL;
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
char *url = mp_obj_str_get_str(args[1]);
char *filepath = mp_obj_str_get_str(args[2]);
http_param = (http_param_t *)aos_malloc(sizeof(http_param_t));
if (!http_param) {
goto done;
}
memset(http_param, 0, sizeof(http_param_t));
http_param->buffer = http_buffer;
http_param->url = url;
http_param->filepath = filepath;
// aos_task_new_ext(&http_task, "amp http download task",
// task_http_download_func, http_param, 1024 * 8, AOS_DEFAULT_APP_PRI + 3);
task_http_download_func(url, filepath);
done:
if (http_buffer)
aos_free(http_buffer);
if (http_param && http_param->params)
cJSON_free(http_param->params);
if (http_param)
aos_free(http_param);
return mp_obj_new_str(http_client_obj->client_data.response_buf, strlen(http_client_obj->client_data.response_buf));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_http_request, 3, obj_http_request);
STATIC mp_obj_t obj_HTTPConnection(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "enter %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
http_client_obj_t *http_client_obj = (http_client_obj_t *)self;
if (http_client_obj == NULL) {
LOGE(LOG_TAG, "http_client_obj is NULL\n");
return mp_const_none;
}
return mp_obj_new_str(http_client_obj->client_data.response_buf, strlen(http_client_obj->client_data.response_buf));
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_HTTPConnection, 2, obj_HTTPConnection);
STATIC const mp_rom_map_elem_t http_client_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_client) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_set_header), MP_ROM_PTR(&mp_obj_http_client_set_header) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_set_data), MP_ROM_PTR(&mp_obj_http_client_set_data) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_get), MP_ROM_PTR(&mp_obj_http_client_get) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_put), MP_ROM_PTR(&mp_obj_http_client_put) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_post), MP_ROM_PTR(&mp_obj_http_client_post) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_send), MP_ROM_PTR(&mp_obj_http_client_send) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_recv), MP_ROM_PTR(&mp_obj_http_client_recv) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_conn), MP_ROM_PTR(&mp_obj_http_client_conn) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_header), MP_ROM_PTR(&mp_obj_http_client_header) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_get_response_code), MP_ROM_PTR(&mp_obj_get_res_code) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_get_response_header), MP_ROM_PTR(&mp_obj_get_res_header_value) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_get_response), MP_ROM_PTR(&mp_obj_get_response) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_add_text), MP_ROM_PTR(&mp_obj_add_text) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_add_file), MP_ROM_PTR(&mp_obj_add_file) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_delete), MP_ROM_PTR(&mp_obj_delete) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_reset), MP_ROM_PTR(&mp_obj_reset) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_prepare), MP_ROM_PTR(&mp_obj_http_client_prepare) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_unprepare), MP_ROM_PTR(&mp_obj_http_client_unprapare) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_obj_http_client_close) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_download), MP_ROM_PTR(&mp_obj_http_download) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_request), MP_ROM_PTR(&mp_obj_http_request) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_HTTPConnection), MP_ROM_PTR(&mp_obj_HTTPConnection) },
};
STATIC MP_DEFINE_CONST_DICT(http_client_module_globals, http_client_module_globals_table);
const mp_obj_type_t http_client_type = {
.base = { &mp_type_type },
.name = MP_QSTR_client,
.print = http_client_print,
.make_new = http_client_new,
.locals_dict = (mp_obj_dict_t *)&http_client_module_globals,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/network/http/aos/httpclient.c | C | apache-2.0 | 27,506 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "amp_task.h"
#include "board_config.h"
#include "httpclient.h"
#include "py_defines.h"
#include "amp_list.h"
#include "cJSON.h"
#define MOD_STR "HTTP"
#define HTTP_BUFF_SIZE 2048
#define HTTP_HEADER_SIZE 1024
#define HTTP_HEADER_COUNT 8
#define HTTP_REQUEST_PARAMS_LEN_MAX 2048
#define HTTP_SEND_RECV_TIMEOUT 10000
#define HTTP_REQUEST_TIMEOUT 30000
#define HTTP_DEFAULT_HEADER_NAME "content-type"
#define HTTP_DEFAULT_HEADER_DATA "application/json"
#define HTTP_CRLF "\r\n"
static int http_header_index = 0;
typedef struct {
char *name;
char *data;
} http_header_t;
typedef struct {
char *url;
char *filepath;
int method;
http_header_t http_header[HTTP_HEADER_COUNT];
uint32_t timeout;
char *params;
char *buffer;
int params_len;
int js_cb_ref;
} http_param_t;
static char *strncasestr(const char *str, const char *key)
{
int len;
if (!str || !key)
return NULL;
len = strlen(key);
if (len == 0)
return NULL;
while (*str) {
if (!strncasecmp(str, key, len))
return str;
++str;
}
return NULL;
}
static void parse_url(const char *url, char *uri)
{
char url_dup[1024] = { 0 };
if (url == NULL) {
amp_warn(MOD_STR, "url is null");
return;
}
memcpy(url_dup, url, strlen(url));
char *start = NULL;
char *p_slash = NULL;
#if 1
const char *protocol = "https";
#else
const char *protocol = "http";
#endif
if (strncmp(url_dup, protocol, strlen(protocol)) == 0) {
start = url_dup + strlen(protocol) + 3;
p_slash = strchr(start, '/');
if (p_slash != NULL) {
memcpy(uri, p_slash, strlen(p_slash));
*p_slash = '\0';
} else {
memcpy(uri, '/', 1);
}
}
}
static void http_request_notify(void *pdata)
{
http_param_t *msg = (http_param_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx, msg->js_cb_ref);
duk_push_string(ctx, msg->buffer);
if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
be_unref(ctx, msg->js_cb_ref);
aos_free(msg->buffer);
if (msg->params)
aos_free(msg->params);
aos_free(msg);
duk_gc(ctx, 0);
}
char customer_header[HTTP_HEADER_SIZE] = { 0 };
char rsp_buf[HTTP_BUFF_SIZE];
char req_buf[HTTP_BUFF_SIZE];
/* create task for http download */
static void task_http_download_func(void *arg)
{
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
http_param_t *param = (http_param_t *)arg;
int num = 0;
int ret;
// 字符串偶现丢失,不知原因,暂时写死,by梓同
// char * req_url = param->url;
// int fd = aos_open(param->filepath, O_CREAT | O_RDWR | O_APPEND);
char *req_url =
"http://wangguan-498.oss-cn-beijing.aliyuncs.com/SHOPAD/public/"
"mould5.png";
int fd = aos_open("/data/http_text.png", O_CREAT | O_RDWR | O_APPEND);
memset(rsp_buf, 0, sizeof(rsp_buf));
client_data.response_buf = rsp_buf;
client_data.response_buf_len = sizeof(rsp_buf);
ret = httpclient_conn(&client, req_url);
if (!ret) {
ret = httpclient_send(&client, req_url, HTTP_GET, &client_data);
do {
ret = httpclient_recv(&client, &client_data);
printf(
"response_content_len=%d, "
"retrieve_len=%d,content_block_len=%d\n",
client_data.response_content_len, client_data.retrieve_len, client_data.content_block_len);
printf("ismore=%d\n", client_data.is_more);
num = aos_write(fd, client_data.response_buf, client_data.content_block_len);
if (num > 0) {
printf("aos_write num=%d\n", num);
}
} while (client_data.is_more);
}
ret = aos_sync(fd);
param->buffer = "http download success";
httpclient_clse(&client);
amp_task_schedule_call(http_request_notify, param);
aos_task_exit(0);
}
/* create task for http request */
static void task_http_request_func(void *arg)
{
char *url = NULL;
uint32_t timeout = 0;
int http_method = 0;
int i = 0;
int ret = 0;
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
http_param_t *param = (http_param_t *)arg;
url = param->url;
timeout = param->timeout;
http_method = param->method;
amp_debug(MOD_STR, "task_http_request_func url: %s", url);
amp_debug(MOD_STR, "task_http_request_func method: %d", http_method);
amp_debug(MOD_STR, "task_http_request_func timeout: %d", timeout);
memset(rsp_buf, 0, HTTP_BUFF_SIZE);
client_data.response_buf = rsp_buf;
client_data.response_buf_len = sizeof(rsp_buf);
aos_msleep(50); /* need do things after state changed in main task */
for (i = 0; i < http_header_index; i++) {
pyamp_httpc_construct_header(customer_header, HTTP_HEADER_SIZE, param->http_header[i].name,
param->http_header[i].data);
}
http_header_index = 0;
httpclient_set_custom_header(&client, customer_header);
if (http_method == HTTP_GET) {
amp_info(MOD_STR, "http GET request=%s,timeout=%d\r\n", url, timeout);
ret = httpclient_get(&client, url, &client_data);
if (ret >= 0) {
amp_info(MOD_STR, "GET Data received: %s, len=%d \r\n", client_data.response_buf,
client_data.response_buf_len);
strcpy(param->buffer, client_data.response_buf);
}
} else if (http_method == HTTP_POST) {
amp_info(MOD_STR, "http POST request=%s,post_buf=%s,timeout=%d\r\n", url, param->params, timeout);
memset(req_buf, 0, sizeof(req_buf));
strcpy(req_buf,
"tab_index=0&count=3&group_id=6914830518563373582&item_id="
"6914830518563373581&aid=1768");
client_data.post_buf = req_buf;
client_data.post_buf_len = sizeof(req_buf);
client_data.post_content_type = "application/x-www-form-urlencoded";
ret = httpclient_post(&client, "https://www.ixigua.com/tlb/comment/article/v5/tab_comments/", &client_data);
if (ret >= 0) {
amp_info(MOD_STR, "POST Data received: %s, len=%d \r\n", client_data.response_buf,
client_data.response_buf_len);
strcpy(param->buffer, client_data.response_buf);
}
} else if (http_method == HTTP_PUT) {
amp_info(MOD_STR, "http PUT request=%s,data=%s,timeout=%d\r\n", url, param->params, timeout);
client_data.post_buf = param->params;
client_data.post_buf_len = param->params_len;
ret = httpclient_put(&client, url, &client_data);
if (ret >= 0) {
amp_info(MOD_STR, "Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len);
strcpy(param->buffer, client_data.response_buf);
}
} else {
ret = httpclient_get(&client, url, &client_data);
if (ret >= 0) {
amp_info(MOD_STR, "Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len);
strcpy(param->buffer, client_data.response_buf);
}
}
amp_task_schedule_call(http_request_notify, param);
aos_task_exit(0);
return;
}
static duk_ret_t native_http_download(duk_context *ctx)
{
http_param_t *http_param = NULL;
char *http_buffer = NULL;
aos_task_t http_task;
if (!duk_is_object(ctx, 0)) {
amp_warn(MOD_STR, "invalid parameter\n");
goto done;
}
http_param = (http_param_t *)aos_malloc(sizeof(http_param_t));
if (!http_param) {
amp_warn(MOD_STR, "allocate memory failed\n");
goto done;
}
memset(http_param, 0, sizeof(http_param_t));
http_param->buffer = http_buffer;
/* get http request url */
duk_get_prop_string(ctx, 0, "url");
if (!duk_is_string(ctx, -1)) {
amp_debug(MOD_STR, "request url is invalid");
goto done;
}
http_param->url = duk_get_string(ctx, 1);
duk_pop(ctx);
amp_debug(MOD_STR, "url: %s", http_param->url);
/* get http download filepath */
duk_get_prop_string(ctx, 0, "filepath");
if (!duk_is_string(ctx, -1)) {
amp_debug(MOD_STR, "filepath is invalid");
goto done;
}
http_param->filepath = duk_get_string(ctx, 1);
duk_pop(ctx);
amp_debug(MOD_STR, "filepath: %s", http_param->filepath);
/* callback */
if (duk_get_prop_string(ctx, 0, "success")) {
duk_dup(ctx, -1);
http_param->js_cb_ref = be_ref(ctx);
} else {
http_param->js_cb_ref = -1;
}
aos_task_new_ext(&http_task, "amp http download task", task_http_download_func, http_param, 1024 * 8,
ADDON_TSK_PRIORRITY);
duk_push_int(ctx, 0);
return 1;
done:
if (http_buffer)
aos_free(http_buffer);
if (http_param && http_param->params)
cJSON_free(http_param->params);
if (http_param)
aos_free(http_param);
duk_push_int(ctx, -1);
return 1;
}
static duk_ret_t native_http_request(duk_context *ctx)
{
http_param_t *http_param = NULL;
char *http_buffer = NULL;
const char *method = NULL;
cJSON *param_root;
int http_method = 0;
int timeout = 0;
char localip[32];
int i;
aos_task_t http_task;
if (!duk_is_object(ctx, 0)) {
amp_warn(MOD_STR, "invalid parameter\n");
goto done;
}
// amp_system.c中netmgr_wifi_get_ip方法没有实现,暂时注释掉这部分 by梓同
// if (amp_get_ip(localip) != 0)
// {
// amp_warn(MOD_STR, "network not ready\r\n");
// goto done;
// }
http_param = (http_param_t *)aos_malloc(sizeof(http_param_t));
if (!http_param) {
amp_warn(MOD_STR, "allocate memory failed\n");
goto done;
}
memset(http_param, 0, sizeof(http_param_t));
http_buffer = aos_malloc(HTTP_BUFF_SIZE + 1);
if (!http_buffer) {
amp_warn(MOD_STR, "allocate memory failed\n");
goto done;
}
memset(http_buffer, 0, HTTP_BUFF_SIZE + 1);
http_param->buffer = http_buffer;
/* get http request url */
duk_get_prop_string(ctx, 0, "url");
if (!duk_is_string(ctx, -1)) {
amp_debug(MOD_STR, "request url is invalid");
goto done;
}
http_param->url = duk_get_string(ctx, 1);
duk_pop(ctx);
/* get http request method */
if (duk_get_prop_string(ctx, 0, "method")) {
if (duk_is_string(ctx, -1)) {
method = duk_get_string(ctx, -1);
if (strcmp(method, "GET") == 0) {
http_method = HTTP_GET; /* GET */
} else if (strcmp(method, "POST") == 0) {
http_method = HTTP_POST; /* POST */
} else if (strcmp(method, "PUT") == 0) {
http_method = HTTP_PUT; /* PUT */
} else {
http_method = HTTP_GET;
}
http_param->method = http_method;
}
} else {
http_param->method = HTTP_GET;
}
duk_pop(ctx);
/* get http request timeout */
if (duk_get_prop_string(ctx, 0, "timeout")) {
if (duk_is_number(ctx, -1)) {
timeout = duk_get_number(ctx, -1);
http_param->timeout = timeout;
} else {
http_param->timeout = HTTP_REQUEST_TIMEOUT;
}
} else {
http_param->timeout = HTTP_REQUEST_TIMEOUT;
}
if (http_param->timeout <= 0) {
http_param->timeout = HTTP_REQUEST_TIMEOUT;
}
duk_pop(ctx);
/* get http request headers */
if (duk_get_prop_string(ctx, 0, "headers")) {
duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY);
while (duk_next(ctx, -1, 1)) {
// amp_debug(MOD_STR, "key=%s, value=%s ", duk_to_string(ctx, -2),
// duk_to_string(ctx, -1));
if (!duk_is_string(ctx, -2) || !duk_is_string(ctx, -1)) {
amp_debug(MOD_STR, "get header failed, index is: %d", http_header_index);
break;
}
http_param->http_header[http_header_index].name = duk_to_string(ctx, -2);
http_param->http_header[http_header_index].data = duk_to_string(ctx, -1);
http_header_index++;
duk_pop_2(ctx);
}
} else {
http_param->http_header[0].name = HTTP_DEFAULT_HEADER_NAME;
http_param->http_header[0].data = HTTP_DEFAULT_HEADER_DATA;
http_header_index++;
}
/* get http request params */
if (duk_get_prop_string(ctx, 0, "params")) {
// duk_enum(ctx, -1, DUK_ENUM_OWN_PROPERTIES_ONLY);
// param_root = cJSON_CreateObject();
// if (!param_root) {
// amp_error(MOD_STR, "alloc param json object fail");
// goto done;
// }
// while (duk_next(ctx, -1, 1)) {
// if (!duk_is_string(ctx, -2) || !duk_is_string(ctx, -1)) {
// amp_error(MOD_STR, "get params fail");
// break;
// }
// cJSON_AddStringToObject(param_root, duk_to_string(ctx, -2),
// duk_to_string(ctx, -1)); duk_pop_2(ctx);
// }
// http_param->params = cJSON_PrintUnformatted(param_root);
// http_param->params_len = strlen(http_param->params);
// amp_error(MOD_STR, "params: %s, len %d", http_param->params,
// http_param->params_len); cJSON_Delete(param_root);
if (duk_is_string(ctx, -1)) {
http_param->params = duk_get_string(ctx, -1);
http_param->params_len = strlen(http_param->params);
amp_debug(MOD_STR, "params: %s, len %d", http_param->params, http_param->params_len);
}
} else {
amp_debug(MOD_STR, "%s: params not contained", __func__);
}
amp_debug(MOD_STR, "url: %s", http_param->url);
amp_debug(MOD_STR, "method: %d", http_param->method);
amp_debug(MOD_STR, "timeout: %d", http_param->timeout);
for (i = 0; i < http_header_index; i++) {
amp_debug(MOD_STR, "headers: %s:%s", http_param->http_header[i].name, http_param->http_header[i].data);
}
/* callback */
if (duk_get_prop_string(ctx, 0, "success")) {
duk_dup(ctx, -1);
http_param->js_cb_ref = be_ref(ctx);
} else {
http_param->js_cb_ref = -1;
}
aos_task_new_ext(&http_task, "amp http task", task_http_request_func, http_param, 1024 * 8, ADDON_TSK_PRIORRITY);
duk_push_int(ctx, 0);
return 1;
done:
if (http_buffer)
aos_free(http_buffer);
if (http_param && http_param->params)
cJSON_free(http_param->params);
if (http_param)
aos_free(http_param);
duk_push_int(ctx, -1);
return 1;
}
void module_http_register(void)
{
duk_context *ctx = be_get_context();
duk_push_object(ctx);
/* request */
AMP_ADD_FUNCTION("request", native_http_request, 1);
AMP_ADD_FUNCTION("download", native_http_download, 1);
// AMP_ADD_FUNCTION("upload", native_http_upload, 1);
duk_put_prop_string(ctx, -2, "HTTP");
}
| YifuLiu/AliOS-Things | components/py_engine/modules/network/http/aos/httputility.c | C | apache-2.0 | 15,369 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_HTTP
#include "aos/kernel.h"
#include "cJSON.h"
#include "httpclient.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-HTTP"
#define MOD_STR "HTTP"
#define HTTP_BUFF_SIZE (12 * 1024)
#define HTTP_HEADER_SIZE 2048
#define HTTP_HEADER_COUNT 8
#define HTTP_REQUEST_PARAMS_LEN_MAX 2048
#define HTTP_SEND_RECV_TIMEOUT 10000
#define HTTP_REQUEST_TIMEOUT 30000
#define HTTP_DEFAULT_HEADER_NAME "content-type"
#define HTTP_DEFAULT_HEADER_DATA "application/json"
#define HTTP_CRLF "\r\n"
#define ADDON_TSK_PRIORRITY (AOS_DEFAULT_APP_PRI + 3)
static int http_header_index = 0;
typedef struct {
char *name;
char *data;
} http_header_t;
typedef struct {
char *url;
char *filepath;
int method;
http_header_t http_header[HTTP_HEADER_COUNT];
uint32_t timeout;
char *params;
char *rec_data_buffer;
char *rec_header_buffer;
int params_len;
mp_obj_t cb;
} http_param_t;
extern const mp_obj_type_t http_client_type;
static char *strncasestr(const char *str, const char *key)
{
int len;
if (!str || !key)
return NULL;
len = strlen(key);
if (len == 0)
return NULL;
while (*str) {
if (!strncasecmp(str, key, len))
return str;
++str;
}
return NULL;
}
static void parse_url(const char *url, char *uri)
{
char url_dup[1024] = { 0 };
if (url == NULL) {
LOGD(LOG_TAG, "url is null");
return;
}
memcpy(url_dup, url, strlen(url));
char *start = NULL;
char *p_slash = NULL;
#if 1
const char *protocol = "https";
#else
const char *protocol = "http";
#endif
if (strncmp(url_dup, protocol, strlen(protocol)) == 0) {
start = url_dup + strlen(protocol) + 3;
p_slash = strchr(start, '/');
if (p_slash != NULL) {
memcpy(uri, p_slash, strlen(p_slash));
*p_slash = '\0';
} else {
memcpy(uri, '/', 1);
}
}
}
int32_t pyamp_httpc_construct_header(char *buf, uint16_t buf_size, const char *name, const char *data)
{
uint32_t hdr_len;
uint32_t hdr_data_len;
int32_t hdr_length;
if (buf == NULL || buf_size == 0 || name == NULL || data == NULL) {
return HTTP_EARG;
}
hdr_len = strlen(name);
hdr_data_len = strlen(data);
hdr_length = hdr_len + hdr_data_len + 4;
if (hdr_length < 0 || hdr_length > buf_size) {
return HTTP_ENOBUFS;
}
memcpy(buf, name, hdr_len);
buf += hdr_len;
memcpy(buf, ": ", 2);
buf += 2;
memcpy(buf, data, hdr_data_len);
buf += hdr_data_len;
memcpy(buf, HTTP_CRLF, 2);
return hdr_length;
}
static void http_request_notify(void *pdata)
{
http_param_t *msg = (http_param_t *)pdata;
char *header_buf = msg->rec_header_buffer;
char *body_buf = msg->rec_data_buffer;
int32_t header_len = strlen(header_buf);
int32_t body_len = strlen(body_buf);
LOGD(LOG_TAG, "header is %s \r\n", header_buf);
LOGD(LOG_TAG, "header len is %d \r\n", header_len);
LOGD(LOG_TAG, "buf is %s \r\n", body_buf);
LOGD(LOG_TAG, "buf len is %d \r\n", body_len);
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
if (header_len != 0) {
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, header_len, header_buf, "header");
} else {
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, 0, NULL, "header");
}
if (body_len != 0) {
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, body_len, body_buf, "body");
} else {
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, 0, NULL, "body");
}
callback_to_python_LoBo(msg->cb, mp_const_none, carg);
}
static void http_download_notify(void *pdata)
{
http_param_t *msg = (http_param_t *)pdata;
LOGD(LOG_TAG, "buf is %s \r\n", msg->rec_data_buffer);
LOGD(LOG_TAG, "buf len is %d \r\n", strlen(msg->rec_data_buffer));
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_SINGLE);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, strlen(msg->rec_data_buffer), msg->rec_data_buffer, NULL);
callback_to_python_LoBo(msg->cb, mp_const_none, carg);
}
static char customer_header[HTTP_HEADER_SIZE] = { 0 };
static char rsp_header[HTTP_HEADER_SIZE] = { 0 };
static char rsp_buf[HTTP_BUFF_SIZE];
static char req_buf[HTTP_BUFF_SIZE];
/* create task for http download */
static void task_http_download_func(void *arg)
{
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
http_param_t *http_param = (http_param_t *)arg;
int num = 0;
int ret, i = 0;
bool result = false;
char *header = "Accept: */*\r\n";
char *req_url = http_param->url;
if (!aos_access(http_param->filepath, 0)) {
aos_remove(http_param->filepath);
}
int fd = aos_open(http_param->filepath, O_CREAT | O_RDWR | O_TRUNC);
if (fd < 0) {
printf("aos open fd %d fail\n", fd);
result = false;
goto end;
}
memset(rsp_buf, 0, sizeof(rsp_buf));
client_data.response_buf = rsp_buf;
client_data.response_buf_len = sizeof(rsp_buf);
client_data.header_buf = rsp_header;
client_data.header_buf_len = HTTP_HEADER_SIZE;
httpclient_set_custom_header(&client, header);
ret = httpclient_conn(&client, req_url);
if (!ret) {
ret = httpclient_send(&client, req_url, HTTP_GET, &client_data);
do {
ret = httpclient_recv(&client, &client_data);
// printf("response_content_len=%d,
// retrieve_len=%d,content_block_len=%d\n",
// client_data.response_content_len,client_data.retrieve_len,client_data.content_block_len);
// printf("ismore=%d\n", client_data.is_more);
num = aos_write(fd, client_data.response_buf, client_data.content_block_len);
if (num > 0) {
// printf("aos_write num=%d\n", num);
} else {
result = false;
break;
}
} while (client_data.is_more);
if (client_data.response_content_len == 0)
result = false;
else
result = true;
} else {
result = false;
printf("[%s]httpclient_conn fail, ret : %d\n", __func__, ret);
}
aos_close(fd);
httpclient_clse(&client);
end:
if (result) {
if (http_param->rec_data_buffer)
strcpy(http_param->rec_data_buffer, "success");
} else {
if (http_param->rec_data_buffer)
strcpy(http_param->rec_data_buffer, "fail");
}
http_download_notify(http_param);
if (http_param && http_param->rec_data_buffer) {
aos_free(http_param->rec_data_buffer);
}
if (http_param && http_param->rec_header_buffer) {
aos_free(http_param->rec_header_buffer);
}
if (http_param) {
aos_free(http_param);
}
aos_task_exit(0);
}
/* create task for http request */
static void task_http_request_func(void *arg)
{
char *url = NULL;
uint32_t timeout = 0;
int http_method = 0;
int i = 0;
int ret = 0;
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
http_param_t *http_param = (http_param_t *)arg;
url = http_param->url;
timeout = http_param->timeout;
http_method = http_param->method;
LOGD(LOG_TAG, "task_http_request_func url: %s", url);
LOGD(LOG_TAG, "task_http_request_func method: %d", http_method);
LOGD(LOG_TAG, "task_http_request_func timeout: %d", timeout);
memset(rsp_buf, 0, HTTP_BUFF_SIZE);
client_data.response_buf = rsp_buf;
client_data.response_buf_len = sizeof(rsp_buf);
client_data.header_buf = rsp_header;
client_data.header_buf_len = HTTP_HEADER_SIZE;
aos_msleep(50); /* need do things after state changed in main task */
uint32_t len = 0;
for (i = 0; i < http_header_index; i++) {
len = pyamp_httpc_construct_header(customer_header + len, HTTP_HEADER_SIZE - len,
http_param->http_header[i].name, http_param->http_header[i].data);
}
http_header_index = 0;
httpclient_set_custom_header(&client, customer_header);
if (http_method == HTTP_GET) {
LOGD(LOG_TAG, "http GET request=%s,timeout=%d\r\n", url, timeout);
ret = httpclient_get(&client, url, &client_data);
if (ret >= 0) {
LOGD(LOG_TAG, "GET Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len);
strcpy(http_param->rec_data_buffer, client_data.response_buf);
strcpy(http_param->rec_header_buffer, client_data.header_buf);
}
} else if (http_method == HTTP_HEAD) {
LOGD(LOG_TAG, "http HEAD request=%s,timeout=%d\r\n", url, timeout);
ret = httpclient_head(&client, url, &client_data);
if (ret >= 0) {
LOGD(LOG_TAG, "HEAD Data received: %s, len=%d \r\n", client_data.response_buf,
client_data.response_buf_len);
strcpy(http_param->rec_data_buffer, client_data.response_buf);
strcpy(http_param->rec_header_buffer, client_data.header_buf);
}
} else if (http_method == HTTP_POST) {
LOGD(LOG_TAG, "http POST request=%s,post_buf=%s,timeout=%d\r\n", url, http_param->params, timeout);
memset(req_buf, 0, sizeof(req_buf));
strcpy(req_buf, http_param->params);
client_data.post_buf = req_buf;
client_data.post_buf_len = sizeof(req_buf);
client_data.post_content_type = "application/x-www-form-urlencoded";
ret = httpclient_post(&client, url, &client_data);
if (ret >= 0) {
LOGD(LOG_TAG, "POST Data received: %s, len=%d \r\n", client_data.response_buf,
client_data.response_buf_len);
strcpy(http_param->rec_data_buffer, client_data.response_buf);
strcpy(http_param->rec_header_buffer, client_data.header_buf);
}
} else if (http_method == HTTP_PUT) {
LOGD(LOG_TAG, "http PUT request=%s,data=%s,timeout=%d\r\n", url, http_param->params, timeout);
memset(req_buf, 0, sizeof(req_buf));
strcpy(req_buf, http_param->params);
client_data.post_buf = req_buf;
client_data.post_buf_len = sizeof(req_buf);
client_data.post_content_type = "application/x-www-form-urlencoded";
ret = httpclient_put(&client, url, &client_data);
if (ret >= 0) {
LOGD(LOG_TAG, "Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len);
strcpy(http_param->rec_data_buffer, client_data.response_buf);
strcpy(http_param->rec_header_buffer, client_data.header_buf);
}
} else if (http_method == HTTP_DELETE) {
LOGD(LOG_TAG, "http DELETE request=%s,data=%s,timeout=%d\r\n", url, http_param->params, timeout);
memset(req_buf, 0, sizeof(req_buf));
strcpy(req_buf, http_param->params);
client_data.post_buf = req_buf;
client_data.post_buf_len = sizeof(req_buf);
client_data.post_content_type = "application/x-www-form-urlencoded";
ret = httpclient_put(&client, url, &client_data);
if (ret >= 0) {
LOGD(LOG_TAG, "Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len);
strcpy(http_param->rec_data_buffer, client_data.response_buf);
strcpy(http_param->rec_header_buffer, client_data.header_buf);
}
} else {
ret = httpclient_get(&client, url, &client_data);
if (ret >= 0) {
LOGD(LOG_TAG, "Data received: %s, len=%d \r\n", client_data.response_buf, client_data.response_buf_len);
strcpy(http_param->rec_data_buffer, client_data.response_buf);
strcpy(http_param->rec_header_buffer, client_data.header_buf);
}
}
httpclient_clse(&client);
http_request_notify(http_param);
if (http_param && http_param->rec_data_buffer) {
aos_free(http_param->rec_data_buffer);
}
if (http_param && http_param->rec_header_buffer) {
aos_free(http_param->rec_header_buffer);
}
if (http_param) {
aos_free(http_param);
}
LOGD(LOG_TAG, " task_http_request_func end \r\n ");
aos_task_exit(0);
return;
}
STATIC mp_obj_t http_download(mp_obj_t data, mp_obj_t callback)
{
http_param_t *http_param = NULL;
char *http_buffer = NULL;
char *http_header_buffer = NULL;
const char *url = NULL;
const char *filepath = NULL;
aos_task_t http_task;
http_param = (http_param_t *)aos_malloc(sizeof(http_param_t));
if (!http_param) {
LOGD(LOG_TAG, "allocate memory failed\n");
goto done;
}
memset(http_param, 0, sizeof(http_param_t));
http_buffer = aos_malloc(32 + 1);
if (!http_buffer) {
LOGE(LOG_TAG, "allocate memory failed\n");
goto done;
}
memset(http_buffer, 0, 32 + 1);
http_param->rec_data_buffer = http_buffer;
http_header_buffer = aos_malloc(HTTP_HEADER_SIZE + 1);
if (!http_header_buffer) {
LOGE(LOG_TAG, "allocate memory failed\n");
goto done;
}
memset(http_header_buffer, 0, HTTP_HEADER_SIZE + 1);
http_param->rec_header_buffer = http_header_buffer;
/* get http download url */
mp_obj_t index = mp_obj_new_str_via_qstr("url", 3);
url = mp_obj_str_get_str(mp_obj_dict_get(data, index));
http_param->url = url;
/* get http download filepath */
index = mp_obj_new_str_via_qstr("filepath", 8);
filepath = mp_obj_str_get_str(mp_obj_dict_get(data, index));
http_param->filepath = filepath;
/* callback */
http_param->cb = callback;
aos_task_new_ext(&http_task, "amp http download task", task_http_download_func, http_param, 1024 * 8,
ADDON_TSK_PRIORRITY);
return mp_obj_new_int(0);
done:
if (http_buffer) {
aos_free(http_buffer);
}
if (http_header_buffer) {
aos_free(http_header_buffer);
}
if (http_param) {
aos_free(http_param);
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_http_download, http_download);
static mp_obj_t http_request(mp_obj_t data, mp_obj_t callback)
{
http_param_t *http_param = NULL;
char *http_buffer = NULL;
char *http_header_buffer = NULL;
const char *method = NULL;
const char *url = NULL;
cJSON *param_root;
int http_method = 0;
int timeout = 0;
char localip[32];
int i;
aos_task_t http_task;
if (!mp_obj_is_dict_or_ordereddict(data)) {
LOGE(LOG_TAG, "%s param type error, param type must be dict\r\n", __func__);
return mp_const_none;
}
http_param = (http_param_t *)aos_malloc(sizeof(http_param_t));
if (!http_param) {
LOGE(LOG_TAG, "allocate memory failed\n");
goto done;
}
memset(http_param, 0, sizeof(http_param_t));
http_buffer = aos_malloc(HTTP_BUFF_SIZE + 1);
if (!http_buffer) {
LOGE(LOG_TAG, "allocate memory failed\n");
goto done;
}
memset(http_buffer, 0, HTTP_BUFF_SIZE + 1);
http_param->rec_data_buffer = http_buffer;
http_header_buffer = aos_malloc(HTTP_HEADER_SIZE + 1);
if (!http_header_buffer) {
LOGE(LOG_TAG, "allocate memory failed\n");
goto done;
}
memset(http_header_buffer, 0, HTTP_HEADER_SIZE + 1);
http_param->rec_header_buffer = http_header_buffer;
/* get http request url */
mp_obj_t index = mp_obj_new_str_via_qstr("url", 3);
url = mp_obj_str_get_str(mp_obj_dict_get(data, index));
http_param->url = url;
/* get http request method */
index = mp_obj_new_str_via_qstr("method", 6);
method = mp_obj_str_get_str(mp_obj_dict_get(data, index));
if (strcmp(method, "GET") == 0) {
http_method = HTTP_GET; /* GET */
} else if (strcmp(method, "HEAD") == 0) {
http_method = HTTP_HEAD; /* HEAD */
} else if (strcmp(method, "POST") == 0) {
http_method = HTTP_POST; /* POST */
} else if (strcmp(method, "PUT") == 0) {
http_method = HTTP_PUT; /* PUT */
} else if (strcmp(method, "DELETE") == 0) {
http_method = HTTP_DELETE; /* DELETE */
} else {
http_method = HTTP_GET;
}
http_param->method = http_method;
/* get http request timeout */
index = mp_obj_new_str_via_qstr("timeout", 7);
timeout = mp_obj_get_int(mp_obj_dict_get(data, index));
http_param->timeout = timeout;
LOGD(LOG_TAG, "timeout is : %d", http_param->timeout);
/* get http request headers */
index = mp_obj_new_str_via_qstr("headers", 7);
mp_obj_t header = mp_obj_dict_get(data, index);
if (header == MP_OBJ_NULL) {
// pass
http_param->http_header[0].name = HTTP_DEFAULT_HEADER_NAME;
http_param->http_header[0].data = HTTP_DEFAULT_HEADER_DATA;
http_header_index++;
} else if (mp_obj_is_type(header, &mp_type_dict)) {
// dictionary
mp_map_t *map = mp_obj_dict_get_map(header);
// assert(args2_len + 2 * map->used <= args2_alloc); // should have
// enough, since kw_dict_len is in this case hinted correctly above
for (size_t i = 0; i < map->alloc; i++) {
if (mp_map_slot_is_filled(map, i)) {
// the key must be a qstr, so intern it if it's a string
mp_obj_t key = map->table[i].key;
if (!mp_obj_is_qstr(key)) {
key = mp_obj_str_intern_checked(key);
}
http_header_index = i;
http_param->http_header[http_header_index].name = mp_obj_str_get_str(map->table[i].key);
http_param->http_header[http_header_index].data = mp_obj_str_get_str(map->table[i].value);
}
}
}
index = mp_obj_new_str_via_qstr("params", 6);
mp_obj_t params = mp_obj_dict_get(data, index);
http_param->params = mp_obj_str_get_str(params);
http_param->params_len = strlen(http_param->params);
LOGD(LOG_TAG, "url: %s", http_param->url);
LOGD(LOG_TAG, "method: %d", http_param->method);
LOGD(LOG_TAG, "timeout: %d", http_param->timeout);
for (i = 0; i < http_header_index; i++) {
LOGD(LOG_TAG, MOD_STR, "headers: %s:%s", http_param->http_header[i].name, http_param->http_header[i].data);
}
/* callback */
http_param->cb = callback;
aos_task_new_ext(&http_task, "amp http task", task_http_request_func, http_param, 1024 * 8, ADDON_TSK_PRIORRITY);
return mp_obj_new_int(0);
done:
if (http_buffer) {
aos_free(http_buffer);
}
if (http_header_buffer) {
aos_free(http_header_buffer);
}
if (http_param) {
aos_free(http_param);
}
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_http_request, http_request);
STATIC const mp_rom_map_elem_t http_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_http) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_request), MP_ROM_PTR(&mp_obj_http_request) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_download), MP_ROM_PTR(&mp_obj_http_download) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_client), MP_ROM_PTR(&http_client_type) },
};
STATIC MP_DEFINE_CONST_DICT(http_locals_dict, http_locals_dict_table);
const mp_obj_module_t mp_module_http = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&http_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_http, mp_module_http, MICROPY_PY_HTTP);
#endif | YifuLiu/AliOS-Things | components/py_engine/modules/network/http/aos/modhttp.c | C | apache-2.0 | 19,796 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_HTTP
#include "esp_event.h"
#include "esp_http_client.h"
#include "esp_log.h"
#include "esp_netif.h"
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "hapy_http_client.h"
#include "nvs_flash.h"
#include "utility.h"
#define LOG_TAG "HTTP_CLIENT"
static int8_t resp_header_buffer[HTTP_HEADER_SIZE];
static int8_t *resp_body_buffer = NULL;
static hapy_http_param_t http_param_download = { 0 };
static hapy_http_param_t http_param_request = { 0 };
extern const uint8_t server_cert_pem_start[] asm("_binary_ca_cert_pem_start");
extern const uint8_t server_cert_pem_end[] asm("_binary_ca_cert_pem_end");
static char *_dirname(const char *path)
{
const char *last_slash = strrchr(path, '/');
if (last_slash == NULL) {
ESP_LOGE(LOG_TAG, "_dirname: no slash in given path:%s", path);
return NULL;
}
char *ret = malloc(last_slash + 1 - path);
if (ret == NULL) {
ESP_LOGE(LOG_TAG, "_dirname: no memory");
return NULL;
}
memcpy(ret, path, last_slash - path);
ret[last_slash - path] = '\0';
return ret;
}
/*
* https://gist.github.com/ChisholmKyle/0cbedcd3e64132243a39
*/
/* recursive mkdir based on
http://nion.modprobe.de/blog/archives/357-Recursive-directory-creation.html
*/
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#define PATH_MAX_STRING_SIZE 256
/* recursive mkdir */
static int mkdir_p(const char *dir, const mode_t mode)
{
char tmp[PATH_MAX_STRING_SIZE];
char *p = NULL;
struct stat sb;
size_t len;
/* copy path */
len = strnlen(dir, PATH_MAX_STRING_SIZE);
if (len == 0 || len == PATH_MAX_STRING_SIZE) {
return -1;
}
memcpy(tmp, dir, len);
tmp[len] = '\0';
/* remove trailing slash */
if (tmp[len - 1] == '/') {
tmp[len - 1] = '\0';
}
/* check if path exists and is a directory */
if (stat(tmp, &sb) == 0) {
if (S_ISDIR(sb.st_mode)) {
return 0;
}
}
/* recursive mkdir */
for (p = tmp + 1; *p; p++) {
if (*p == '/') {
*p = 0;
/* test path */
if (stat(tmp, &sb) != 0) {
/* path does not exist - create directory */
if (mkdir(tmp, mode) < 0) {
return -1;
}
} else if (!S_ISDIR(sb.st_mode)) {
/* not a directory */
return -1;
}
*p = '/';
}
}
/* test path */
if (stat(tmp, &sb) != 0) {
/* path does not exist - create directory */
if (mkdir(tmp, mode) < 0) {
return -1;
}
} else if (!S_ISDIR(sb.st_mode)) {
/* not a directory */
return -1;
}
return 0;
}
static int32_t hapy_http_construct_header(char *buf, uint16_t buf_size, const char *name, const char *data)
{
uint32_t hdr_len;
uint32_t hdr_data_len;
int32_t hdr_length;
if (buf == NULL || buf_size == 0 || name == NULL || data == NULL) {
ESP_LOGE(LOG_TAG, "hapy_http_construct_header args error !!!!\n");
return 0;
}
hdr_len = strlen(name);
hdr_data_len = strlen(data);
hdr_length = hdr_len + hdr_data_len + 4;
if (hdr_length < 0 || hdr_length > buf_size) {
ESP_LOGE(LOG_TAG, "hapy_http_construct_header hdr_length error, hdr_length[%d], buf_size[%d] !!!!\n",
hdr_length, buf_size);
return 0;
}
memcpy(buf, name, hdr_len);
buf += hdr_len;
memcpy(buf, ": ", 2);
buf += 2;
memcpy(buf, data, hdr_data_len);
buf += hdr_data_len;
memcpy(buf, HTTP_CRLF, 2);
return hdr_length;
}
static void http_request_notify(hapy_http_param_t *http_param_request, int8_t *header_buf, int8_t *body_buf)
{
int32_t header_len = 0;
int32_t body_len = 0;
if (header_buf != NULL) {
header_len = strlen(header_buf);
}
if (body_buf != NULL) {
body_len = strlen(body_buf);
}
ESP_LOGE(LOG_TAG, "http_request_notify with header_len=%d, body_len=%d", header_len, body_len);
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
if (header_len != 0) {
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, header_len, header_buf, "header");
} else {
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, 0, NULL, "header");
}
if (body_len != 0) {
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, body_len, body_buf, "body");
} else {
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, 0, NULL, "body");
}
callback_to_python_LoBo(http_param_request->cb, mp_const_none, carg);
}
static void http_download_notify(hapy_http_param_t *http_param_download, http_dl_status ret)
{
char *status = "fali";
if (ret == HTTP_DL_STATUS_OK) {
status = "success";
} else if (ret == HTTP_DL_STATUS_FAIL) {
status = "fail";
} else if (ret == HTTP_DL_STATUS_PATH_NULL) {
status = "url_null";
} else {
status = "unknown";
}
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_SINGLE);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_STR, strlen(status), status, NULL);
callback_to_python_LoBo(http_param_download->cb, mp_const_none, carg);
}
static esp_err_t _http_request_event_handler(esp_http_client_event_t *evt)
{
static int32_t body_len = 0;
static int32_t header_len = 0;
switch (evt->event_id) {
case HTTP_EVENT_ERROR:
ESP_LOGE(LOG_TAG, "HTTP_EVENT_ERROR");
break;
case HTTP_EVENT_ON_CONNECTED:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_ON_CONNECTED");
break;
case HTTP_EVENT_HEADER_SENT:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_HEADER_SENT");
break;
case HTTP_EVENT_ON_HEADER:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_ON_HEADER[%d], key=%s, value=%s", header_len, evt->header_key, evt->header_value);
header_len += hapy_http_construct_header(resp_header_buffer + header_len, HTTP_HEADER_SIZE - header_len,
evt->header_key, evt->header_value);
break;
case HTTP_EVENT_ON_DATA:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_ON_DATA, body_len=%d, data_len=%d", body_len, evt->data_len);
/*
* Check for chunked encoding is added as the URL for chunked encoding used
* in this example returns binary data. However, event handler can also be
* used in case chunked encoding is used.
*/
if (!esp_http_client_is_chunked_response(evt->client)) {
ESP_LOGD(LOG_TAG, "HTTP_EVENT_ON_DATA, len = %d", esp_http_client_get_content_length(evt->client));
if (resp_body_buffer == NULL) {
resp_body_buffer = (char *)calloc(esp_http_client_get_content_length(evt->client) + 1, 1);
body_len = 0;
if (resp_body_buffer == NULL) {
ESP_LOGE(LOG_TAG, "Failed to allocate memory for output buffer");
return ESP_FAIL;
}
}
memcpy(resp_body_buffer + body_len, evt->data, evt->data_len);
body_len += evt->data_len;
}
break;
case HTTP_EVENT_ON_FINISH:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_ON_FINISH");
// Add end for resp_header_buffer and resp_body_buffer
resp_header_buffer[header_len] = 0;
if (resp_body_buffer != NULL) {
resp_body_buffer[body_len] = 0;
}
header_len = 0;
body_len = 0;
break;
case HTTP_EVENT_DISCONNECTED:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_DISCONNECTED");
int32_t mbedtls_err = 0;
esp_err_t err = esp_tls_get_and_clear_last_error(evt->data, &mbedtls_err, NULL);
if (err != 0) {
ESP_LOGE(LOG_TAG, "Last esp error code: 0x%x", err);
ESP_LOGE(LOG_TAG, "Last mbedtls failure: 0x%x", mbedtls_err);
}
header_len = 0;
body_len = 0;
break;
}
return ESP_OK;
}
static esp_err_t _http_download_event_handler(esp_http_client_event_t *evt)
{
switch (evt->event_id) {
case HTTP_EVENT_ERROR:
ESP_LOGE(LOG_TAG, "HTTP_EVENT_ERROR");
break;
case HTTP_EVENT_ON_CONNECTED:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_ON_CONNECTED");
break;
case HTTP_EVENT_HEADER_SENT:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_HEADER_SENT");
break;
case HTTP_EVENT_ON_FINISH:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_ON_FINISH");
break;
case HTTP_EVENT_DISCONNECTED:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_DISCONNECTED");
break;
default:
ESP_LOGD(LOG_TAG, "HTTP_EVENT_DEFAULT");
}
return ESP_OK;
}
/* create task for http download */
static void task_http_download_func(void *arg)
{
http_dl_status ret = HTTP_DL_STATUS_FAIL;
if (http_param_download.filepath == NULL) {
ESP_LOGE(LOG_TAG, "http download filepath NULL");
ret = HTTP_DL_STATUS_PATH_NULL;
goto finish;
}
/* Check folder and create if not exist */
const char *path = _dirname(http_param_download.filepath);
struct stat stat_i = { 0 };
if (stat(path, &stat_i) < 0) {
ESP_LOGI(LOG_TAG, "path %s not exist, create recursive", path);
mkdir_p(path, 0755); // 0755 表示8进制的755,0不能删除
}
free(path);
int fd = open(http_param_download.filepath, O_CREAT | O_RDWR | O_TRUNC);
if (fd < 0) {
ESP_LOGE(LOG_TAG, "failed to open file[%s], fd = %d\n", http_param_download.filepath, fd);
ret = HTTP_DL_STATUS_FAIL;
goto finish;
}
esp_http_client_config_t config = { 0 };
config.url = http_param_download.url;
config.event_handler = _http_download_event_handler;
esp_http_client_handle_t client = esp_http_client_init(&config);
if (client == NULL) {
ESP_LOGE(LOG_TAG, "Failed to initialise HTTP connection");
goto fail;
}
esp_err_t err = esp_http_client_open(client, 0);
if (err != ESP_OK) {
ESP_LOGE(LOG_TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
goto fail;
}
uint8_t buffer[MAX_HTTP_RECV_BUFFER + 1] = { 0 };
int32_t content_length = esp_http_client_fetch_headers(client);
ESP_LOGD(LOG_TAG, "HTTP Stream reader Status = %d, content_length = %d", esp_http_client_get_status_code(client),
esp_http_client_get_content_length(client));
int32_t total_read_len = 0;
int32_t read_len = 0;
while (total_read_len < content_length) {
read_len = esp_http_client_read(client, buffer, MAX_HTTP_RECV_BUFFER);
if (read_len < 0) {
ESP_LOGE(LOG_TAG, "Error read data, read_len = %d", read_len);
break;
} else if (read_len == 0) {
ESP_LOGD(LOG_TAG, "read finished...");
break;
}
buffer[read_len] = 0;
total_read_len += read_len;
ESP_LOGD(LOG_TAG, "read_len = %d, cb=%p", read_len, http_param_download.cb);
/* write data to file */
int num = write(fd, buffer, read_len);
if (num < 0) {
goto fail;
}
}
ret = (esp_http_client_get_status_code(client) == 200) ? HTTP_DL_STATUS_OK : HTTP_DL_STATUS_FAIL;
fail:
if (client != NULL) {
esp_http_client_close(client);
esp_http_client_cleanup(client);
}
if (fd >= 0) {
close(fd);
fd = -1;
}
finish:
http_download_notify(&http_param_download, ret);
vTaskDelete(NULL);
}
/* create task for http request */
static void task_http_request_func(void *arg)
{
/**
* NOTE: All the configuration parameters for http_client must be spefied
* either in URL or as host and path parameters. If host and path parameters
* are not set, query parameter will be ignored. In such cases, query
* parameter should be specified in URL.
*
* If URL as well as host and path parameters are specified, values of host
* and path will be considered.
*/
resp_body_buffer = NULL;
memset(resp_header_buffer, 0, HTTP_HEADER_SIZE);
esp_http_client_config_t config = { 0 };
config.url = http_param_request.url;
config.query = "HaaS_Python";
config.event_handler = _http_request_event_handler;
config.timeout_ms = http_param_request.timeout;
esp_http_client_handle_t client = esp_http_client_init(&config);
for (int32_t i = 0; i < http_param_request.header_size; i++) {
esp_http_client_set_header(client, http_param_request.http_header[i].name,
http_param_request.http_header[i].data);
}
switch (http_param_request.method) {
case HTTP_GET:
{
esp_http_client_set_method(client, HTTP_METHOD_GET);
break;
}
case HTTP_POST:
{
esp_http_client_set_method(client, HTTP_METHOD_POST);
esp_http_client_set_post_field(client, http_param_request.params, strlen(http_param_request.params));
break;
}
case HTTP_PUT:
{
esp_http_client_set_method(client, HTTP_METHOD_PUT);
break;
}
case HTTP_PATCH:
{
esp_http_client_set_method(client, HTTP_METHOD_PATCH);
esp_http_client_set_post_field(client, NULL, 0);
break;
}
case HTTP_DELETE:
{
esp_http_client_set_method(client, HTTP_METHOD_DELETE);
break;
}
case HTTP_HEAD:
{
esp_http_client_set_method(client, HTTP_METHOD_HEAD);
break;
}
}
esp_err_t err = esp_http_client_perform(client);
if (err == ESP_OK) {
ESP_LOGD(LOG_TAG, "HTTP POST Status = %d, content_length = %d", esp_http_client_get_status_code(client),
esp_http_client_get_content_length(client));
} else {
printf("HTTP POST request failed: %s\r\n", esp_err_to_name(err));
}
esp_http_client_cleanup(client);
// notify to python app
http_request_notify(&http_param_request, resp_header_buffer, resp_body_buffer);
if (resp_body_buffer != NULL) {
free(resp_body_buffer);
resp_body_buffer = NULL;
}
ESP_LOGD(LOG_TAG, "Finish http request");
vTaskDelete(NULL);
}
STATIC mp_obj_t http_download(mp_obj_t data, mp_obj_t callback)
{
const int8_t *url = NULL;
const int8_t *filepath = NULL;
memset(&http_param_download, 0, sizeof(hapy_http_param_t));
/* get http download url */
mp_obj_t index = mp_obj_new_str_via_qstr("url", strlen("url"));
url = mp_obj_str_get_str(mp_obj_dict_get(data, index));
http_param_download.url = url;
/* get http download filepath */
index = mp_obj_new_str_via_qstr("filepath", strlen("filepath"));
filepath = mp_obj_str_get_str(mp_obj_dict_get(data, index));
http_param_download.filepath = filepath;
/* callback */
http_param_download.cb = callback;
ESP_LOGD(LOG_TAG, "callback = %p\n", callback);
xTaskCreate(&task_http_download_func, "task_http_download_func", 8192, NULL, ADDON_TSK_PRIORRITY, NULL);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_http_download, http_download);
static mp_obj_t http_request(mp_obj_t data, mp_obj_t callback)
{
const int8_t *method = NULL;
const int8_t *url = NULL;
int32_t http_method = 0;
int32_t timeout = 0;
if (!mp_obj_is_dict_or_ordereddict(data)) {
ESP_LOGE(LOG_TAG, "%s param type error, param type must be dict\r\n", __func__);
return mp_obj_new_int(-EINVAL);
}
memset(&http_param_request, 0, sizeof(hapy_http_param_t));
resp_body_buffer = NULL;
/* get http request url */
mp_obj_t index = mp_obj_new_str_via_qstr("url", 3);
url = mp_obj_str_get_str(mp_obj_dict_get(data, index));
http_param_request.url = url;
/* get http request method */
index = mp_obj_new_str_via_qstr("method", 6);
method = mp_obj_str_get_str(mp_obj_dict_get(data, index));
if (strcmp(method, "GET") == 0) {
http_method = HTTP_GET;
} else if (strcmp(method, "HEAD") == 0) {
http_method = HTTP_HEAD;
} else if (strcmp(method, "POST") == 0) {
http_method = HTTP_POST;
} else if (strcmp(method, "PUT") == 0) {
http_method = HTTP_PUT;
} else if (strcmp(method, "DELETE") == 0) {
http_method = HTTP_DELETE;
} else {
http_method = HTTP_GET;
}
http_param_request.method = http_method;
/* get http request timeout */
index = mp_obj_new_str_via_qstr("timeout", 7);
timeout = mp_obj_get_int(mp_obj_dict_get(data, index));
http_param_request.timeout = timeout;
/* get http request headers */
index = mp_obj_new_str_via_qstr("headers", 7);
mp_obj_t header = mp_obj_dict_get(data, index);
if (header == MP_OBJ_NULL) {
http_param_request.http_header[0].name = HTTP_DEFAULT_HEADER_NAME;
http_param_request.http_header[0].data = HTTP_DEFAULT_HEADER_DATA;
http_param_request.header_size = 1;
} else if (mp_obj_is_type(header, &mp_type_dict)) {
// dictionary
mp_map_t *map = mp_obj_dict_get_map(header);
// assert(args2_len + 2 * map->used <= args2_alloc); // should have
// enough, since kw_dict_len is in this case hinted correctly above
for (size_t i = 0; i < map->alloc; i++) {
if (mp_map_slot_is_filled(map, i)) {
// the key must be a qstr, so intern it if it's a string
mp_obj_t key = map->table[i].key;
if (!mp_obj_is_qstr(key)) {
key = mp_obj_str_intern_checked(key);
}
http_param_request.http_header[i].name = mp_obj_str_get_str(map->table[i].key);
http_param_request.http_header[i].data = mp_obj_str_get_str(map->table[i].value);
http_param_request.header_size = i + 1;
}
}
}
/* get params */
index = mp_obj_new_str_via_qstr("params", 6);
mp_obj_t params = mp_obj_dict_get(data, index);
http_param_request.params = mp_obj_str_get_str(params);
/* callback */
http_param_request.cb = callback;
ESP_LOGD(LOG_TAG, "url: %s", http_param_request.url);
ESP_LOGD(LOG_TAG, "method: %d", http_param_request.method);
ESP_LOGD(LOG_TAG, "timeout: %d", http_param_request.timeout);
for (int i = 0; i < http_param_request.header_size; i++) {
ESP_LOGD(LOG_TAG, "headers: %s:%s", http_param_request.http_header[i].name,
http_param_request.http_header[i].data);
}
ESP_LOGD(LOG_TAG, "params: %s", http_param_request.params);
xTaskCreate(&task_http_request_func, "task_http_request_func", 8192, NULL, ADDON_TSK_PRIORRITY, NULL);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_http_request, http_request);
STATIC const mp_rom_map_elem_t http_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_http) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_request), MP_ROM_PTR(&mp_obj_http_request) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_download), MP_ROM_PTR(&mp_obj_http_download) },
{ MP_ROM_QSTR(MP_QSTR_OK), MP_ROM_INT(HTTP_DL_STATUS_OK) },
{ MP_ROM_QSTR(MP_QSTR_FAIL), MP_ROM_INT(HTTP_DL_STATUS_FAIL) },
{ MP_ROM_QSTR(MP_QSTR_NULL), MP_ROM_INT(HTTP_DL_STATUS_PATH_NULL) },
};
STATIC MP_DEFINE_CONST_DICT(http_locals_dict, http_locals_dict_table);
const mp_obj_module_t mp_module_http = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&http_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_http, mp_module_http, MICROPY_PY_HTTP);
#endif // MICROPY_PY_HTTP
| YifuLiu/AliOS-Things | components/py_engine/modules/network/http/esp32/modhttp.c | C | apache-2.0 | 19,772 |
#ifndef _HAAS_HTTP_CLIENT_H
#define _HAAS_HTTP_CLIENT_H
#include <stdint.h>
#include "py/obj.h"
#define MAX_HTTP_RECV_BUFFER 512
#define MAX_HTTP_RESP_BUFFER 2048
#define HTTP_HEADER_SIZE 1024
#define HTTP_HEADER_COUNT 16
#define HTTP_DEFAULT_HEADER_NAME "content-type"
#define HTTP_DEFAULT_HEADER_DATA "application/json"
#define HTTP_CRLF "\r\n"
#define ADDON_TSK_PRIORRITY (20)
typedef struct {
const char *name;
const char *data;
} http_header_t;
typedef struct {
const char *url;
const char *filepath;
int32_t method;
uint32_t timeout;
const char *params;
mp_obj_t cb;
http_header_t http_header[HTTP_HEADER_COUNT];
int32_t header_size;
} hapy_http_param_t;
typedef enum {
HTTP_DL_STATUS_OK = 0,
HTTP_DL_STATUS_FAIL = -1,
HTTP_DL_STATUS_PATH_NULL = -2,
} http_dl_status;
#endif | YifuLiu/AliOS-Things | components/py_engine/modules/network/http/hapy_http_client.h | C | apache-2.0 | 884 |
/*
* This file is part of the MicroPython project, http://micropython.org/
*
* Development of the code in this file was sponsored by Microbric Pty Ltd
* and Mnemote Pty Ltd
*
* The MIT License (MIT)
*
* Copyright (c) 2016, 2017 Nick Moore @mnemote
* Copyright (c) 2017 "Eric Poulsen" <eric@zyxod.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#if MICROPY_PY_NETWORK
#include "lwip/dns.h"
#include "modnetwork.h"
#include "netmgr_wifi.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/nlr.h"
#include "py/objlist.h"
#include "py/runtime.h"
#include "shared/netutils/netutils.h"
#include "ulog/ulog.h"
#define LOG_TAG "mod_network"
#define DNS_MAIN TCPIP_ADAPTER_DNS_MAIN
#define MODNETWORK_INCLUDE_CONSTANTS (1)
#define QS(x) (uintptr_t) MP_OBJ_NEW_QSTR(x)
typedef enum {
WIFI_MODE_NULL = 0x00,
WIFI_MODE_STA = 0x01,
WIFI_MODE_AP = 0x02,
} wifi_mode_t;
enum {
STAT_IDLE = 1000,
STAT_CONNECTING = 1001,
STAT_GOT_IP = 1010,
};
NORETURN void _haas_wifi_exceptions(wifi_result_t e)
{
switch (e) {
case RET_WIFI_COMMON_FAIL:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Common Fail"));
case RET_WIFI_INVALID_ARG:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Invalid Arguments"));
case RET_WIFI_INVALID_PASSWORD:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Invalid Password"));
case RET_WIFI_MEMORY_ERROR:
mp_raise_OSError(MP_ENOMEM);
case RET_WIFI_INIT_FAIL:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Init Fail"));
case RET_WIFI_NOT_INITED:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Not Initialized"));
case RET_WIFI_STATUS_ERROR:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Request In Error Status"));
case RET_WIFI_SCAN_REQ_FAIL:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Scan Fail To Start"));
case RET_WIFI_SCAN_NO_AP_FOUND:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Can Not Find Any SSID"));
case RET_WIFI_NO_SUITABLE_NETWORK:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi No Suitable Network To Connect"));
case RET_WIFI_CONN_REQ_FAIL:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Connect Fail To Start"));
case RET_WIFI_CONN_FAIL:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Connect Procedure Result In Fail"));
case RET_WIFI_CONN_NO_SSID_CONFIG:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi No Saved SSID Config To Connect"));
case RET_WIFI_DISC_FAIL:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Disconnect Procedure Result In Fail"));
case RET_WIFI_WPS_NOT_FOUND:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Can Not Find WPS AP"));
case RET_WIFI_WPS_REQ_FAIL:
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("Wifi Fail To Start WPS"));
default:
mp_raise_msg_varg(&mp_type_RuntimeError, MP_ERROR_TEXT("Wifi Unknown Error 0x%04x"), e);
}
}
static inline void haas_exceptions(wifi_result_t e)
{
if (e != RET_WIFI_OK) {
_haas_wifi_exceptions(e);
}
}
#define HAAS_EXCEPTIONS(x) \
do { \
haas_exceptions(x); \
} while (0);
typedef struct _wlan_if_obj_t {
mp_obj_base_t base;
netmgr_hdl_t hdl; // can get through netmgr_wifi_get_dev
netmgr_wifi_mode_t if_id;
} wlan_if_obj_t;
const mp_obj_type_t wlan_if_type;
STATIC const wlan_if_obj_t wlan_sta_obj = { { &wlan_if_type }, NETMGR_WIFI_MODE_STA };
STATIC const wlan_if_obj_t wlan_ap_obj = { { &wlan_if_type }, NETMGR_WIFI_MODE_AP };
// Set to "true" if haas_wifi_start() was called
static bool wifi_started = false;
// Set to "true" if the STA interface is requested to be connected by the
// user, used for automatic reassociation.
static bool wifi_sta_connect_requested = false;
// Set to "true" if the STA interface is connected to wifi and has IP address.
static bool wifi_sta_connected = false;
// Store the current status. 0 means None here, safe to do so as first enum
// value is WIFI_REASON_UNSPECIFIED=1.
static uint8_t wifi_sta_disconn_reason = 0;
static int wifi_set_mac(netmgr_hdl_t hdl, uint8_t *mac)
{
return ioctl(hdl, WIFI_DEV_CMD_SET_MAC, mac);
}
static int wifi_get_mac(netmgr_hdl_t hdl, uint8_t *mac)
{
return ioctl(hdl, WIFI_DEV_CMD_GET_MAC, mac);
}
static int wifi_get_rssi(netmgr_hdl_t hdl, int *rssi)
{
int state = -1;
wifi_ap_record_t out = { 0 };
int ret = ioctl(hdl, WIFI_DEV_CMD_STA_GET_LINK_STATUS, &out));
if (ret == 0) {
memcpy(rssi, &out.rssi, sizeof(out.rssi));
state = 0;
}
return state;
}
// This function is called by the system-event task and so runs in a different
// thread to the main MicroPython task. It must not raise any Python
// exceptions.
static wifi_result_t event_handler(void *ctx, system_event_t *event)
{
switch (event->event_id) {
case CONN_STATE_DISCONNECTING:
LOGD(LOG_TAG, "wifi CONN_STATE_DISCONNECTING");
break;
case CONN_STATE_DISCONNECTED:
LOGI(LOG_TAG, "wifi STA_DISCONNECTED");
break;
case CONN_STATE_CONNECTING:
LOGD(LOG_TAG, "wifi CONN_STATE_CONNECTING");
break;
case CONN_STATE_CONNECTED:
LOGI(LOG_TAG, "wifi CONN_STATE_CONNECTED");
break;
case CONN_STATE_OBTAINING_IP:
LOGI(LOG_TAG, "wifi CONN_STATE_OBTAINING_IP");
wifi_sta_connected = true;
wifi_sta_disconn_reason = 0;
break;
case CONN_STATE_NETWORK_CONNECTED:
LOGI(LOG_TAG, "wifi CONN_STATE_NETWORK_CONNECTED");
break;
case CONN_STATE_FAILED:
LOGI(LOG_TAG, "wifi CONN_STATE_FAILED");
break;
default:
LOGI(LOG_TAG, "event %d", event->event_id);
break;
}
return RET_WIFI_OK;
}
STATIC void require_if(mp_obj_t wlan_if, int if_no)
{
wlan_if_obj_t *self = MP_OBJ_TO_PTR(wlan_if);
if (self->if_id != if_no) {
mp_raise_msg(&mp_type_OSError,
if_no == NETMGR_WIFI_MODE_STA ? MP_ERROR_TEXT("STA required") : MP_ERROR_TEXT("AP required"));
}
}
STATIC mp_obj_t get_wlan(size_t n_args, const mp_obj_t *args)
{
static int initialized = 0;
if (!initialized) {
LOGD(LOG_TAG, "modnetwork get WLAN start");
HAAS_EXCEPTIONS(event_service_init(NULL));
HAAS_EXCEPTIONS(netmgr_service_init(NULL));
LOGD(LOG_TAG, "modnetwork got WLAN");
initialized = 1;
}
int idx = (n_args > 0) ? mp_obj_get_int(args[0]) : NETMGR_WIFI_MODE_STA;
if (idx == NETMGR_WIFI_MODE_STA) {
return MP_OBJ_FROM_PTR(&wlan_sta_obj);
} else if (idx == NETMGR_WIFI_MODE_AP) {
return MP_OBJ_FROM_PTR(&wlan_ap_obj);
} else {
mp_raise_ValueError(MP_ERROR_TEXT("invalid WLAN interface identifier"));
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(get_wlan_obj, 0, 1, get_wlan);
STATIC mp_obj_t wlan_initialize()
{
static int initialized = 0;
if (!initialized) {
LOGD(LOG_TAG, "modnetwork Initializing start");
HAAS_EXCEPTIONS(event_service_init(NULL));
HAAS_EXCEPTIONS(netmgr_service_init(NULL));
LOGD(LOG_TAG, "modnetwork Initialized");
initialized = 1;
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(wlan_initialize_obj, wlan_initialize);
STATIC mp_obj_t haas_wlan_active(size_t n_args, const mp_obj_t *args)
{
wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
wifi_mode_t mode;
if (!wifi_started) {
mode = WIFI_MODE_NULL;
} else {
HAAS_EXCEPTIONS(haas_wlan_wifi_get_mode(&mode));
}
int bit = (self->if_id == NETMGR_WIFI_MODE_STA) ? WIFI_MODE_STA : WIFI_MODE_AP;
if (n_args > 1) {
bool active = mp_obj_is_true(args[1]);
mode = active ? (mode | bit) : (mode & ~bit);
if (mode == WIFI_MODE_NULL) {
if (wifi_started) {
HAAS_EXCEPTIONS(haas_wlan_wifi_stop());
wifi_started = false;
}
} else {
HAAS_EXCEPTIONS(haas_wlan_wifi_set_mode(mode));
if (!wifi_started) {
HAAS_EXCEPTIONS(haas_wlan_wifi_start());
wifi_started = true;
}
}
}
return (mode & bit) ? mp_const_true : mp_const_false;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(haas_wlan_active_obj, 1, 2, haas_wlan_active);
STATIC mp_obj_t haas_wlan_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args)
{
enum {
ARG_ssid,
ARG_password,
ARG_bssid
};
static const mp_arg_t allowed_args[] = {
{ MP_QSTR_, MP_ARG_OBJ, { .u_obj = mp_const_none } },
{ MP_QSTR_, MP_ARG_OBJ, { .u_obj = mp_const_none } },
{ MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, { .u_obj = mp_const_none } },
};
wlan_if_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]);
// parse args
mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)];
mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args);
netmgr_connect_params_t wifi_sta_config = { 0 };
// configure any parameters that are given
if (n_args > 1) {
size_t len;
const char *p;
if (args[ARG_ssid].u_obj != mp_const_none) {
p = mp_obj_str_get_data(args[ARG_ssid].u_obj, &len);
memcpy(wifi_sta_config.wifi_params.ssid, p, MIN(len, sizeof(wifi_sta_config.wifi_params.ssid)));
}
if (args[ARG_password].u_obj != mp_const_none) {
p = mp_obj_str_get_data(args[ARG_password].u_obj, &len);
memcpy(wifi_sta_config.wifi_params.pwd, p, MIN(len, sizeof(wifi_sta_config.wifi_params.pwd)));
}
if (args[ARG_bssid].u_obj != mp_const_none) {
p = mp_obj_str_get_data(args[ARG_bssid].u_obj, &len);
if (len != sizeof(wifi_sta_config.wifi_params.bssid)) {
mp_raise_ValueError(NULL);
}
wifi_sta_config.wifi_params.bssid_set = 1;
memcpy(wifi_sta_config.wifi_params.bssid, p, sizeof(wifi_sta_config.wifi_params.bssid));
}
// HAAS_EXCEPTIONS(haas_wlan_wifi_set_config(NETMGR_WIFI_MODE_STA,
// &wifi_sta_config));
}
// connect to the WiFi AP
MP_THREAD_GIL_EXIT();
HAAS_EXCEPTIONS(netmgr_connect(self->hdl, &wifi_sta_config));
MP_THREAD_GIL_ENTER();
wifi_sta_connect_requested = true;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_KW(haas_wlan_connect_obj, 1, haas_wlan_connect);
STATIC mp_obj_t haas_wlan_disconnect(mp_obj_t self_in)
{
wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
wifi_sta_connect_requested = false;
HAAS_EXCEPTIONS(netmgr_disconnect(self->hdl));
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(haas_wlan_disconnect_obj, haas_wlan_disconnect);
STATIC mp_obj_t haas_wlan_status(size_t n_args, const mp_obj_t *args)
{
wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
if (n_args == 1) {
if (self->if_id == NETMGR_WIFI_MODE_STA) {
// Case of no arg is only for the STA interface
if (wifi_sta_connected) {
// Happy path, connected with IP
return MP_OBJ_NEW_SMALL_INT(STAT_GOT_IP);
} else if (wifi_sta_connect_requested) {
// No connection or error, but is requested = Still connecting
return MP_OBJ_NEW_SMALL_INT(STAT_CONNECTING);
} else if (wifi_sta_disconn_reason == 0) {
// No activity, No error = Idle
return MP_OBJ_NEW_SMALL_INT(STAT_IDLE);
} else {
// Simply pass the error through from haas_wlan-identifier
return MP_OBJ_NEW_SMALL_INT(wifi_sta_disconn_reason);
}
}
return mp_const_none;
}
#if 0
// one argument: return status based on query parameter
switch ((uintptr_t)args[1]) {
case QS(MP_QSTR_stations): {
// return list of connected stations, only if in soft-AP mode
require_if(args[0], NETMGR_WIFI_MODE_AP);
netmgr_wifi_config_t station_list = {0};
HAAS_EXCEPTIONS(netmgr_wifi_get_config(self->hdl, &station_list));
netmgr_wifi_ap_info_t *stations = &station_list.config;
mp_obj_t list = mp_obj_new_list(0, NULL);
for (int i = 0; i < station_list.ap_num; ++i) {
mp_obj_tuple_t *t = mp_obj_new_tuple(1, NULL);
t->items[0] = mp_obj_new_bytes(stations[i].mac, sizeof(stations[i].mac));
mp_obj_list_append(list, t);
}
return list;
}
case QS(MP_QSTR_rssi): {
// return signal of AP, only in STA mode
require_if(args[0], NETMGR_WIFI_MODE_STA);
netmgr_ifconfig_info_t info;
HAAS_EXCEPTIONS(netmgr_get_ifconfig(self->hdl, &info));
return MP_OBJ_NEW_SMALL_INT(info.rssi);
}
default:
mp_raise_ValueError(MP_ERROR_TEXT("unknown status param"));
}
#endif
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(haas_wlan_status_obj, 1, 2, haas_wlan_status);
STATIC mp_obj_t haas_wlan_scan(mp_obj_t self_in)
{
wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
// check that STA mode is active
wifi_mode_t mode;
HAAS_EXCEPTIONS(haas_wlan_wifi_get_mode(&mode));
if ((mode & WIFI_MODE_STA) == 0) {
mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("STA must be active"));
}
mp_obj_t list = mp_obj_new_list(0, NULL);
netmgr_wifi_ap_list_t wifi_ap_records[16] = { 0 };
// XXX how do we scan hidden APs (and if we can scan them, are they really
// hidden?)
MP_THREAD_GIL_EXIT();
int ap_num = netmgr_wifi_scan_result(&wifi_ap_records, 16, NETMGR_WIFI_SCAN_TYPE_FULL);
MP_THREAD_GIL_ENTER();
if ((ap_num != -1) && (ap_num < 16)) {
for (uint16_t i = 0; i < ap_num; i++) {
mp_obj_tuple_t *t = mp_obj_new_tuple(5, NULL);
int8_t *x = memchr(wifi_ap_records[i].ssid, 0, sizeof(wifi_ap_records[i].ssid));
int ssid_len = x ? x - wifi_ap_records[i].ssid : sizeof(wifi_ap_records[i].ssid);
t->items[0] = mp_obj_new_bytes(wifi_ap_records[i].ssid, ssid_len);
t->items[1] = mp_obj_new_bytes(wifi_ap_records[i].bssid, sizeof(wifi_ap_records[i].bssid));
t->items[2] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].ap_power);
t->items[3] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].channel);
t->items[4] = MP_OBJ_NEW_SMALL_INT(wifi_ap_records[i].sec_type);
mp_obj_list_append(list, MP_OBJ_FROM_PTR(t));
}
free(wifi_ap_records);
}
return list;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(haas_wlan_scan_obj, haas_wlan_scan);
STATIC mp_obj_t haas_wlan_isconnected(mp_obj_t self_in)
{
wlan_if_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (self->if_id == NETMGR_WIFI_MODE_STA) {
return mp_obj_new_bool(wifi_sta_connected);
} else {
wifi_sta_list_t sta;
haas_wlan_wifi_ap_get_sta_list(&sta);
return mp_obj_new_bool(sta.num != 0);
}
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(haas_wlan_isconnected_obj, haas_wlan_isconnected);
STATIC mp_obj_t haas_wlan_ifconfig(size_t n_args, const mp_obj_t *args)
{
wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
netmgr_ifconfig_info_t info = { 0 };
if (n_args == 1) {
// get
HAAS_EXCEPTIONS(netmgr_get_ifconfig(self->hdl, &info));
mp_obj_t tuple[4] = {
netutils_format_ipv4_addr((uint8_t *)&info.ip_addr, NETUTILS_BIG),
netutils_format_ipv4_addr((uint8_t *)&info.mask, NETUTILS_BIG),
netutils_format_ipv4_addr((uint8_t *)&info.gw, NETUTILS_BIG),
netutils_format_ipv4_addr((uint8_t *)&info.dns_server, NETUTILS_BIG),
};
return mp_obj_new_tuple(4, tuple);
} else {
// set
if (mp_obj_is_type(args[1], &mp_type_tuple) || mp_obj_is_type(args[1], &mp_type_list)) {
mp_obj_t *items;
mp_obj_get_array_fixed_n(args[1], 4, &items);
netutils_parse_ipv4_addr(items[0], (void *)&info.ip_addr, NETUTILS_BIG);
if (mp_obj_is_integer(items[1])) {
// allow numeric mask, i.e.:
// 24 -> 255.255.255.0
// 16 -> 255.255.0.0
// etc...
uint32_t *m = (uint32_t *)&info.mask;
*m = htonl(0xffffffff << (32 - mp_obj_get_int(items[1])));
} else {
netutils_parse_ipv4_addr(items[1], (void *)&info.mask, NETUTILS_BIG);
}
netutils_parse_ipv4_addr(items[2], (void *)&info.gw, NETUTILS_BIG);
netutils_parse_ipv4_addr(items[3], (void *)&info.dns_server, NETUTILS_BIG);
} else {
// check for the correct string
const char *mode = mp_obj_str_get_str(args[1]);
if (self->if_id != NETMGR_WIFI_MODE_STA || strcmp("dhcp", mode)) {
mp_raise_ValueError(MP_ERROR_TEXT("invalid arguments"));
}
}
HAAS_EXCEPTIONS(netmgr_set_ifconfig(self->hdl, &info));
return mp_const_none;
}
}
MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(haas_wlan_ifconfig_obj, 1, 2, haas_wlan_ifconfig);
STATIC mp_obj_t haas_wlan_config(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs)
{
if (n_args != 1 && kwargs->used != 0) {
mp_raise_TypeError(MP_ERROR_TEXT("either pos or kw args are allowed"));
}
wlan_if_obj_t *self = MP_OBJ_TO_PTR(args[0]);
bool is_wifi = self->if_id == NETMGR_WIFI_MODE_AP || self->if_id == NETMGR_WIFI_MODE_STA;
netmgr_config_t cfg = { 0 };
if (is_wifi) {
HAAS_EXCEPTIONS(netmgr_get_config(self->if_id, &cfg));
}
mp_obj_t val = mp_const_none;
// if (kwargs->used != 0) {
// if (!is_wifi) {
// goto unknown;
// }
// for (size_t i = 0; i < kwargs->alloc; i++) {
// if (mp_map_slot_is_filled(kwargs, i)) {
// int req_if = -1;
// switch ((uintptr_t)kwargs->table[i].key) {
// case QS(MP_QSTR_mac): {
// mp_buffer_info_t bufinfo;
// mp_get_buffer_raise(kwargs->table[i].value, &bufinfo,
// MP_BUFFER_READ); if (bufinfo.len != 6) {
// mp_raise_ValueError(MP_ERROR_TEXT("invalid buffer
// length"));
// }
// HAAS_EXCEPTIONS(wifi_set_mac(self->hdl,
// bufinfo.buf)); break;
// }
// case QS(MP_QSTR_essid): {
// req_if = NETMGR_WIFI_MODE_AP;
// size_t len;
// const char *s =
// mp_obj_str_get_data(kwargs->table[i].value, &len);
// len = MIN(len, sizeof(cfg.ap.ssid));
// memcpy(cfg.ap.ssid, s, len);
// cfg.ap.ssid_len = len;
// break;
// }
// case QS(MP_QSTR_hidden): {
// req_if = NETMGR_WIFI_MODE_AP;
// cfg.ap.ssid_hidden =
// mp_obj_is_true(kwargs->table[i].value); break;
// }
// case QS(MP_QSTR_authmode): {
// req_if = NETMGR_WIFI_MODE_AP;
// cfg.ap.authmode =
// mp_obj_get_int(kwargs->table[i].value); break;
// }
// case QS(MP_QSTR_password): {
// req_if = NETMGR_WIFI_MODE_AP;
// size_t len;
// const char *s =
// mp_obj_str_get_data(kwargs->table[i].value, &len);
// len = MIN(len, sizeof(cfg.ap.password) - 1);
// memcpy(cfg.ap.password, s, len);
// cfg.ap.password[len] = 0;
// break;
// }
// case QS(MP_QSTR_channel): {
// req_if = NETMGR_WIFI_MODE_AP;
// cfg.ap.channel =
// mp_obj_get_int(kwargs->table[i].value); break;
// }
// case QS(MP_QSTR_dhcp_hostname): {
// const char *s =
// mp_obj_str_get_str(kwargs->table[i].value);
// HAAS_EXCEPTIONS(tcpip_adapter_set_hostname(self->if_id,
// s)); break;
// }
// case QS(MP_QSTR_max_clients): {
// req_if = NETMGR_WIFI_MODE_AP;
// cfg.ap.max_connection =
// mp_obj_get_int(kwargs->table[i].value); break;
// }
// default:
// goto unknown;
// }
// // We post-check interface requirements to save on code size
// if (req_if >= 0) {
// require_if(args[0], req_if);
// }
// }
// }
// HAAS_EXCEPTIONS(haas_wlan_wifi_set_config(self->if_id, &cfg));
// return mp_const_none;
// }
// // Get config
// if (n_args != 2) {
// mp_raise_TypeError(MP_ERROR_TEXT("can query only one param"));
// }
// int req_if = -1;
// switch ((uintptr_t)args[1]) {
// case QS(MP_QSTR_mac): {
// uint8_t mac[6];
// switch (self->if_id) {
// case NETMGR_WIFI_MODE_AP: // fallthrough intentional
// case NETMGR_WIFI_MODE_STA:
// HAAS_EXCEPTIONS(wifi_get_mac(self->hdl, mac));
// return mp_obj_new_bytes(mac, sizeof(mac));
// default:
// goto unknown;
// }
// }
// break;
// case QS(MP_QSTR_essid):
// switch (self->if_id) {
// case NETMGR_WIFI_MODE_STA:
// val = mp_obj_new_str((char *)cfg.sta.ssid, strlen((char
// *)cfg.sta.ssid)); break;
// case NETMGR_WIFI_MODE_AP:
// val = mp_obj_new_str((char *)cfg.ap.ssid,
// cfg.ap.ssid_len); break;
// default:
// req_if = NETMGR_WIFI_MODE_AP;
// }
// break;
// case QS(MP_QSTR_hidden):
// req_if = NETMGR_WIFI_MODE_AP;
// val = mp_obj_new_bool(cfg.ap.ssid_hidden);
// break;
// case QS(MP_QSTR_authmode):
// req_if = NETMGR_WIFI_MODE_AP;
// val = MP_OBJ_NEW_SMALL_INT(cfg.ap.authmode);
// break;
// case QS(MP_QSTR_channel):
// req_if = NETMGR_WIFI_MODE_AP;
// val = MP_OBJ_NEW_SMALL_INT(cfg.ap.channel);
// break;
// case QS(MP_QSTR_dhcp_hostname): {
// const char *s;
// HAAS_EXCEPTIONS(tcpip_adapter_get_hostname(self->if_id, &s));
// val = mp_obj_new_str(s, strlen(s));
// break;
// }
// case QS(MP_QSTR_max_clients): {
// val = MP_OBJ_NEW_SMALL_INT(cfg.ap.max_connection);
// break;
// }
// default:
// goto unknown;
// }
// // We post-check interface requirements to save on code size
// if (req_if >= 0) {
// require_if(args[0], req_if);
// }
return val;
unknown:
mp_raise_ValueError(MP_ERROR_TEXT("unknown config param"));
}
MP_DEFINE_CONST_FUN_OBJ_KW(haas_wlan_config_obj, 1, haas_wlan_config);
STATIC const mp_rom_map_elem_t wlan_if_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&haas_wlan_active_obj) },
{ MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&haas_wlan_connect_obj) },
{ MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&haas_wlan_disconnect_obj) },
{ MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&haas_wlan_status_obj) },
{ MP_ROM_QSTR(MP_QSTR_scan), MP_ROM_PTR(&haas_wlan_scan_obj) },
{ MP_ROM_QSTR(MP_QSTR_isconnected), MP_ROM_PTR(&haas_wlan_isconnected_obj) },
{ MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&haas_wlan_config_obj) },
{ MP_ROM_QSTR(MP_QSTR_ifconfig), MP_ROM_PTR(&haas_wlan_ifconfig_obj) },
};
STATIC MP_DEFINE_CONST_DICT(wlan_if_locals_dict, wlan_if_locals_dict_table);
const mp_obj_type_t wlan_if_type = {
{ &mp_type_type },
.name = MP_QSTR_WLAN,
.locals_dict = (mp_obj_t)&wlan_if_locals_dict,
};
STATIC const mp_rom_map_elem_t mp_module_network_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_network) },
{ MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&wlan_initialize_obj) },
{ MP_ROM_QSTR(MP_QSTR_WLAN), MP_ROM_PTR(&get_wlan_obj) },
};
STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals_table);
const mp_obj_module_t mp_module_network = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&mp_module_network_globals,
};
MP_REGISTER_MODULE(MP_QSTR_network, mp_module_network, MICROPY_PY_NETWORK);
#endif | YifuLiu/AliOS-Things | components/py_engine/modules/network/modnetwork.c | C | apache-2.0 | 26,503 |
#ifndef _MOD_NETWORK_H_
#define _MOD_NETWORK_H_
#include "lwip/ip_addr.h"
#define NETWORK_SSID_MAX_LEN (32)
#define NETWORK_PASSWD_MAX_LEN (64)
typedef struct network_wifi_info {
char ssid[NETWORK_SSID_MAX_LEN + 1];
char bssid[6];
int rssi;
} network_wifi_info_t;
typedef struct wifi_ap_info {
char ssid[NETWORK_SSID_MAX_LEN + 1];
char passwd[NETWORK_PASSWD_MAX_LEN + 1];
} wifi_ap_info_t;
enum network_t {
NETWORK_TYPE_WIFI = 0,
NETWORK_TYPE_CELLULAR,
NETWORK_TYPE_ETHERNET,
};
enum network_event_t {
NETWORK_EVT_GOT_IP = 0,
NETWORK_EVT_CONN_FAIL,
NETWORK_EVT_GOT_SSID_PASSWD,
};
int network_qrcode_scan(void *gray, int w, int h, char *ouput, int max_len);
int network_qrscan_result_process(const char *result, char *ssid, char *passwd);
#endif /* _MOD_NETWORK_H_ */
| YifuLiu/AliOS-Things | components/py_engine/modules/network/modnetwork.h | C | apache-2.0 | 822 |
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "cJSON.h"
#include "dev_info.h"
#include "modnetwork.h"
#include "usb_s_uvc_ioctl.h"
#include "zbar.h"
int network_qrcode_scan(void *gray, int w, int h, char *ouput, int max_len)
{
int ret = -1, len = 0;
char *data = NULL;
zbar_image_scanner_t *scanner = NULL;
zbar_image_t *image = NULL;
const zbar_symbol_t *symbol = NULL;
zbar_symbol_type_t type = ZBAR_NONE;
do {
scanner = zbar_image_scanner_create();
if (NULL == scanner) {
break;
}
/* configure the reader */
zbar_image_scanner_set_config(scanner, ZBAR_NONE, ZBAR_CFG_ENABLE, 1);
/* wrap image data */
image = zbar_image_create();
if (NULL == image) {
break;
}
zbar_image_set_format(image, *(int *)"Y800");
zbar_image_set_size(image, w, h);
zbar_image_set_data(image, gray, w * h, NULL);
/* scan the image for barcodes */
ret = zbar_scan_image(scanner, image);
if (0 >= ret) {
break;
}
symbol = zbar_image_first_symbol(image);
for (; symbol; symbol = zbar_symbol_next(symbol)) {
/* do something useful with results */
type = zbar_symbol_get_type(symbol);
if (ZBAR_QRCODE != type) {
printf("zbar code ----> %s, skip\n",
zbar_get_symbol_name(type));
continue;
}
data = (char *)zbar_symbol_get_data(symbol);
len = (unsigned int)zbar_symbol_get_data_length(symbol);
if (data && max_len > len) {
memcpy(ouput, data, len);
ret = len;
}
}
} while (0);
if (image) {
zbar_image_free_data(image);
zbar_image_destroy(image);
}
if (scanner) {
zbar_image_scanner_destroy(scanner);
}
return ret;
}
int network_qrscan_result_process(const char *result, char *ssid, char *passwd)
{
int ret = 0;
cJSON *ssid_elem, *passwd_elem;
cJSON *root = cJSON_Parse(result);
if (root == NULL) {
return 0;
}
// {"ssid":"aaaaa","pwd":"sssddddd"}
ssid_elem = cJSON_GetObjectItem(root, "ssid");
passwd_elem = cJSON_GetObjectItem(root, "pwd");
do {
if (ssid_elem == NULL || passwd_elem == NULL)
break;
if (!cJSON_IsString(ssid_elem) || !cJSON_IsString(passwd_elem))
break;
if (strlen(ssid_elem->valuestring) > NETWORK_SSID_MAX_LEN ||
strlen(passwd_elem->valuestring) > NETWORK_PASSWD_MAX_LEN) {
break;
}
strncpy(ssid, ssid_elem->valuestring, NETWORK_SSID_MAX_LEN);
strncpy(passwd, passwd_elem->valuestring, NETWORK_PASSWD_MAX_LEN);
ret = 1;
} while (0);
cJSON_Delete(root);
return ret;
} | YifuLiu/AliOS-Things | components/py_engine/modules/network/qrcode.c | C | apache-2.0 | 2,928 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_TCP
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#define LOG_TAG "MOD_TCP"
// 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 *ModuleName;
} mp_tcp_obj_t;
STATIC mp_obj_t obj_createSocket(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_tcp_obj_t *driver_obj = (mp_tcp_obj_t *)self;
if (driver_obj == NULL) {
LOGE(LOG_TAG, "driver_obj is NULL\n");
return mp_const_none;
}
LOGD(LOG_TAG, "%s:out\n", __func__);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_tcp_createSocket, 5, obj_createSocket);
STATIC mp_obj_t obj_send(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_tcp_obj_t *driver_obj = (mp_tcp_obj_t *)self;
if (driver_obj == NULL) {
LOGE(LOG_TAG, "driver_obj is NULL\n");
return mp_const_none;
}
LOGD(LOG_TAG, "%s:out\n", __func__);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_tcp_send, 5, obj_send);
STATIC mp_obj_t obj_recv(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_tcp_obj_t *driver_obj = (mp_tcp_obj_t *)self;
if (driver_obj == NULL) {
LOGE(LOG_TAG, "driver_obj is NULL\n");
return mp_const_none;
}
LOGD(LOG_TAG, "%s:out\n", __func__);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_tcp_recv, 5, obj_recv);
STATIC const mp_rom_map_elem_t tcp_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_tcp) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_createSocket), MP_ROM_PTR(&mp_obj_tcp_createSocket) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_send), MP_ROM_PTR(&mp_obj_tcp_send) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_recv), MP_ROM_PTR(&mp_obj_tcp_recv) },
};
STATIC MP_DEFINE_CONST_DICT(tcp_module_globals, tcp_module_globals_table);
const mp_obj_module_t tcp_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&tcp_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_tcp, tcp_module, MICROPY_PY_TCP);
#endif // MICROPY_PY_TCP
| YifuLiu/AliOS-Things | components/py_engine/modules/network/tcp/modtcp.c | C | apache-2.0 | 3,180 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "amp_platform.h"
#include "amp_task.h"
#include "aos_system.h"
#include "aos_tcp.h"
#include "be_inl.h"
#include "board_config.h"
#include "py_defines.h"
#define MOD_STR "TCP"
#define MAX_TCP_RECV_LEN 256
#define MAX_TCP_RECV_TIMEOUT 200
typedef struct {
int sock_id;
char *msg;
int msg_len;
int js_cb_ref;
} tcp_send_param_t;
typedef struct {
int ret;
int js_cb_ref;
} tcp_send_notify_param_t;
typedef struct {
int sock_id;
int js_cb_ref;
} tcp_recv_param_t;
typedef struct {
char *host;
int port;
int js_cb_ref;
} tcp_create_param_t;
typedef struct {
int ret;
int js_cb_ref;
} tcp_create_notify_param_t;
typedef struct {
char buf[MAX_TCP_RECV_LEN];
int recv_len;
int js_cb_ref;
} tcp_recv_notify_param_t;
static char g_tcp_close_flag = 0;
static char g_tcp_recv_flag = 0;
static aos_sem_t g_tcp_close_sem = NULL;
static void tcp_create_notify(void *pdata)
{
tcp_create_notify_param_t *p = (tcp_create_notify_param_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx, p->js_cb_ref);
duk_push_int(ctx, p->ret);
if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
be_unref(ctx, p->js_cb_ref);
aos_free(p);
duk_gc(ctx, 0);
}
static int tcp_create_routine(tcp_create_param_t *create_param)
{
int ret = -1;
tcp_create_notify_param_t *p;
duk_context *ctx = be_get_context();
p = aos_calloc(1, sizeof(tcp_create_notify_param_t));
if (!p) {
amp_warn(MOD_STR, "allocate memory failed");
be_unref(ctx, create_param->js_cb_ref);
goto out;
}
ret = aos_tcp_establish(create_param->host, create_param->port);
if (ret < 0) {
amp_warn(MOD_STR, "tcp establish failed");
}
amp_debug(MOD_STR, "sock_id = %d", ret);
p->js_cb_ref = create_param->js_cb_ref;
p->ret = ret;
py_task_schedule_call(tcp_create_notify, p);
out:
return ret;
}
/*************************************************************************************
* Function: native_udp_create_socket
* 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 duk_ret_t native_tcp_create_socket(duk_context *ctx)
{
int err;
int ret = -1;
int port = 0;
const char *host;
tcp_create_param_t *create_param = NULL;
if (!duk_is_object(ctx, 0) || !duk_is_function(ctx, 1)) {
amp_warn(MOD_STR, "parameter must be (object, function)");
goto out;
}
/* get device certificate */
duk_get_prop_string(ctx, 0, "host");
duk_get_prop_string(ctx, 0, "port");
if (!duk_is_string(ctx, -2) || !duk_is_number(ctx, -1)) {
amp_warn(MOD_STR,
"Parameter 1 must be an object like {host: string, "
"port: uint}");
err = -2;
goto out;
}
host = duk_get_string(ctx, -2);
port = duk_get_number(ctx, -1);
amp_debug(MOD_STR, "host: %s, port: %d", host, port);
create_param = (tcp_create_param_t *)aos_malloc(sizeof(*create_param));
if (!create_param) {
amp_error(MOD_STR, "allocate memory failed");
goto out;
}
duk_dup(ctx, 1);
create_param->host = host;
create_param->port = port;
create_param->js_cb_ref = be_ref(ctx);
ret = tcp_create_routine(create_param);
if (ret < 0) {
amp_warn(MOD_STR, "tcp create socket failed");
goto out;
}
out:
if (create_param) {
aos_free(create_param);
}
duk_push_int(ctx, ret);
return 1;
}
static void tcp_send_notify(void *pdata)
{
tcp_send_notify_param_t *p = (tcp_send_notify_param_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx, p->js_cb_ref);
duk_push_int(ctx, p->ret);
if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
be_unref(ctx, p->js_cb_ref);
aos_free(p);
duk_gc(ctx, 0);
}
/*************************************************************************************
* Function: udp_send_routin
* Description: create a task for blocking sendto call
* Called by:
**************************************************************************************/
static int tcp_send_routine(tcp_send_param_t *send_param)
{
int ret = -1;
tcp_send_notify_param_t *p;
int sock_id;
duk_context *ctx = be_get_context();
sock_id = send_param->sock_id;
ret = aos_tcp_write(sock_id, send_param->msg, send_param->msg_len, 0);
p = aos_calloc(1, sizeof(tcp_send_notify_param_t));
if (!p) {
amp_warn(MOD_STR, "allocate memory failed");
be_unref(ctx, send_param->js_cb_ref);
goto out;
}
p->js_cb_ref = send_param->js_cb_ref;
p->ret = ret;
py_task_schedule_call(tcp_send_notify, p);
ret = 0;
out:
aos_free(send_param->msg);
aos_free(send_param);
return ret;
}
/*************************************************************************************
* Function: native_udp_sendto
* Description: js native addon for
*UDP.send(sock_id,option,buffer_array,function(ret){}) Called by: js api
* Input: sock_id: interger
* options: is a object include options.ip and options.port
* buffer_array: is a array which include message to send
* function(ret): is the callback function which has a ret input
*param Output: return send msg length when send success return error
*number when send fail
**************************************************************************************/
static duk_ret_t native_tcp_send(duk_context *ctx)
{
int ret = -1;
int sock_id;
int i;
int msg_len;
char *msg;
if (!duk_is_number(ctx, 0) || !duk_is_array(ctx, 1) ||
!duk_is_function(ctx, 2)) {
amp_warn(MOD_STR, "parameter must be (number, string, function)");
goto out;
}
sock_id = duk_get_int(ctx, 0);
if (sock_id <= 0) {
amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id);
goto out;
}
msg_len = duk_get_length(ctx, 1);
msg = (char *)aos_malloc(msg_len + 1);
if (!msg) {
amp_warn(MOD_STR, "allocate memory failed");
goto out;
}
for (i = 0; i < msg_len; i++) {
duk_get_prop_index(ctx, 1, i);
msg[i] = duk_get_int(ctx, -1);
duk_pop(ctx);
}
msg[msg_len] = 0;
// const char *send_buf = duk_get_string(ctx, 1);
// msg_len = strlen(send_buf);
// msg = (char *)aos_malloc(msg_len);
// if (msg == NULL) {
// amp_warn(MOD_STR, "allocate memory failed");
// goto out;
// }
// strncpy(msg, send_buf, msg_len);
amp_debug(MOD_STR, "msg is:%s, length is: %d", msg, msg_len);
tcp_send_param_t *send_param =
(tcp_send_param_t *)aos_malloc(sizeof(*send_param));
if (!send_param) {
amp_error(MOD_STR, "allocate memory failed");
aos_free(msg);
goto out;
}
send_param->sock_id = sock_id;
send_param->msg = msg;
send_param->msg_len = msg_len;
duk_dup(ctx, 2);
send_param->js_cb_ref = be_ref(ctx);
tcp_send_routine(send_param);
out:
duk_push_int(ctx, ret);
return 1;
}
static void tcp_recv_notify(void *pdata)
{
int i = 0;
tcp_recv_notify_param_t *p = (tcp_recv_notify_param_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx, p->js_cb_ref);
duk_push_int(ctx, p->recv_len);
int arr_idx = duk_push_array(ctx);
if (p->recv_len > 0) {
for (i = 0; i < p->recv_len; i++) {
duk_push_int(ctx, p->buf[i]);
duk_put_prop_index(ctx, arr_idx, i);
}
}
if (duk_pcall(ctx, 2) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
duk_gc(ctx, 0);
if (p->recv_len < 0) {
be_unref(ctx, p->js_cb_ref);
aos_free(p);
}
}
/*************************************************************************************
* Function: udp_recv_routine
* Description: create a task for blocking recvfrom call
* Called by:
**************************************************************************************/
static void tcp_recv_routine(void *arg)
{
tcp_recv_param_t *recv_param = (tcp_recv_param_t *)arg;
int sock_id;
g_tcp_recv_flag = 1;
sock_id = recv_param->sock_id;
tcp_recv_notify_param_t *p = aos_calloc(1, sizeof(*p));
if (!p) {
amp_warn(MOD_STR, "allocate memory failed");
duk_context *ctx = be_get_context();
be_unref(ctx, recv_param->js_cb_ref);
goto out;
}
while (1) {
p->recv_len =
aos_tcp_read(sock_id, p->buf, sizeof(p->buf), MAX_TCP_RECV_TIMEOUT);
p->js_cb_ref = recv_param->js_cb_ref;
if (p->recv_len != 0) {
py_task_schedule_call(tcp_recv_notify, p);
}
if (p->recv_len < 0) {
// connection closed
amp_error(MOD_STR, "connection closed:%d", p->recv_len);
break;
}
if (g_tcp_close_flag) {
duk_context *ctx = be_get_context();
be_unref(ctx, recv_param->js_cb_ref);
aos_free(p);
break;
}
}
aos_tcp_destroy(sock_id);
out:
aos_free(recv_param);
g_tcp_recv_flag = 0;
aos_sem_signal(&g_tcp_close_sem);
aos_task_exit(0);
return;
}
/*************************************************************************************
* Function: native_udp_recvfrom
* Description: js native addon for
* UDP.recv(sock_id,function(length, buffer_array, src_ip,
*src_port){}) Called by: js api Input: sock_id: interger
* function(length, buffer_array, src_ip, src_port): the callback
*function length: the recv msg length buffer_array: the recv msg buffer src_ip:
*the peer ip string src_port: the peer port which is a interger
*
* Output: return 0 when UDP.recv call ok
* return error number UDP.recv call fail
**************************************************************************************/
static duk_ret_t native_tcp_receive(duk_context *ctx)
{
int ret = -1;
int sock_id = 0;
aos_task_t tcp_recv_task;
tcp_recv_param_t *recv_param;
if (!duk_is_number(ctx, 0) || !duk_is_function(ctx, 1)) {
amp_warn(MOD_STR, "parameter must be number and function");
goto out;
}
sock_id = duk_get_int(ctx, 0);
if (sock_id < 0) {
amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id);
goto out;
}
amp_debug(MOD_STR, "sock_id: %d", sock_id);
recv_param = (tcp_recv_param_t *)aos_calloc(1, sizeof(*recv_param));
if (!recv_param) {
amp_warn(MOD_STR, "allocate memory failed");
goto out;
}
recv_param->sock_id = sock_id;
duk_dup(ctx, 1);
recv_param->js_cb_ref = be_ref(ctx);
ret =
aos_task_new_ext(&tcp_recv_task, "amp tcp recv task", tcp_recv_routine,
recv_param, 1024 * 4, ADDON_TSK_PRIORRITY);
if (ret != 0) {
amp_warn(MOD_STR, "tcp recv task error");
goto out;
}
out:
duk_push_int(ctx, ret);
return 1;
}
/*************************************************************************************
* Function: native_tcp_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 duk_ret_t native_tcp_close(duk_context *ctx)
{
int ret = -1;
int sock_id = 0;
if (!duk_is_number(ctx, 0)) {
amp_warn(MOD_STR, "parameter must be number");
goto out;
}
sock_id = duk_get_int(ctx, 0);
if (sock_id <= 0) {
amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id);
goto out;
}
g_tcp_close_flag = 1;
aos_sem_wait(&g_tcp_close_sem, MAX_TCP_RECV_TIMEOUT + 50);
g_tcp_close_flag = 0;
ret = 0;
out:
duk_push_int(ctx, ret);
return 1;
}
static void module_tcp_source_clean(void)
{
if (g_tcp_recv_flag) {
g_tcp_close_flag = 1;
aos_sem_wait(&g_tcp_close_sem, MAX_TCP_RECV_TIMEOUT + 50);
g_tcp_close_flag = 0;
}
}
void module_tcp_register(void)
{
duk_context *ctx = be_get_context();
if (!g_tcp_close_sem) {
if (aos_sem_new(&g_tcp_close_sem, 0) != 0) {
amp_error(MOD_STR, "create tcp sem fail");
return;
}
}
amp_module_free_register(module_tcp_source_clean);
duk_push_object(ctx);
AMP_ADD_FUNCTION("createSocket", native_tcp_create_socket, 2);
AMP_ADD_FUNCTION("send", native_tcp_send, 3);
AMP_ADD_FUNCTION("recv", native_tcp_receive, 2);
AMP_ADD_FUNCTION("close", native_tcp_close, 1);
duk_put_prop_string(ctx, -2, "TCP");
}
| YifuLiu/AliOS-Things | components/py_engine/modules/network/tcp/module_tcp.c | C | apache-2.0 | 13,352 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_UDP
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#define LOG_TAG "MOD_UDP"
// 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 *ModuleName;
} mp_udp_obj_t;
STATIC mp_obj_t obj_createSocket(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_udp_obj_t *driver_obj = (mp_udp_obj_t *)self;
if (driver_obj == NULL) {
LOGE(LOG_TAG, "driver_obj is NULL\n");
return mp_const_none;
}
LOGD(LOG_TAG, "%s:out\n", __func__);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_udp_createSocket, 5, obj_createSocket);
STATIC mp_obj_t obj_bind(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_udp_obj_t *driver_obj = (mp_udp_obj_t *)self;
if (driver_obj == NULL) {
LOGE(LOG_TAG, "driver_obj is NULL\n");
return mp_const_none;
}
LOGD(LOG_TAG, "%s:out\n", __func__);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_udp_bind, 5, obj_bind);
STATIC mp_obj_t obj_sendto(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_udp_obj_t *driver_obj = (mp_udp_obj_t *)self;
if (driver_obj == NULL) {
LOGE(LOG_TAG, "driver_obj is NULL\n");
return mp_const_none;
}
LOGD(LOG_TAG, "%s:out\n", __func__);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_udp_sendto, 5, obj_sendto);
STATIC mp_obj_t obj_recvfrom(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
void *instance = NULL;
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_base_t *self = (mp_obj_base_t *)MP_OBJ_TO_PTR(args[0]);
mp_udp_obj_t *driver_obj = (mp_udp_obj_t *)self;
if (driver_obj == NULL) {
LOGE(LOG_TAG, "driver_obj is NULL\n");
return mp_const_none;
}
LOGD(LOG_TAG, "%s:out\n", __func__);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_udp_recvfrom, 5, obj_recvfrom);
STATIC const mp_rom_map_elem_t udp_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_udp) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_createSocket), MP_ROM_PTR(&mp_obj_udp_createSocket) },
{ MP_ROM_QSTR(MP_QSTR_bind), MP_ROM_PTR(&mp_obj_udp_bind) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_sendto), MP_ROM_PTR(&mp_obj_udp_sendto) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_recvfrom), MP_ROM_PTR(&mp_obj_udp_recvfrom) },
};
STATIC MP_DEFINE_CONST_DICT(udp_module_globals, udp_module_globals_table);
const mp_obj_module_t udp_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&udp_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_udp, udp_module, MICROPY_PY_UDP);
#endif // MICROPY_PY_UDP
| YifuLiu/AliOS-Things | components/py_engine/modules/network/udp/modudp.c | C | apache-2.0 | 3,963 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include "amp_platform.h"
#include "amp_task.h"
#include "amp_utils.h"
#include "aos_system.h"
#include "aos_udp.h"
#include "be_inl.h"
#include "board_config.h"
#include "py_defines.h"
#ifndef INET_ADDRSTRLEN
#define INET_ADDRSTRLEN 16
#endif
#define MOD_STR "UDP"
#define MAX_UDP_RECV_LEN 256
#define MAX_UDP_RECV_TIMEOUT 200
typedef struct {
char ip[INET_ADDRSTRLEN];
int port;
char *msg;
} udp_options_t;
typedef struct {
int sock_id;
char *msg;
int msg_len;
udp_options_t options;
int js_cb_ref;
} udp_send_param_t;
typedef struct {
int ret;
int js_cb_ref;
} udp_send_notify_param_t;
typedef struct {
int sock_id;
udp_options_t options;
int js_cb_ref;
} udp_recv_param_t;
typedef struct {
char buf[MAX_UDP_RECV_LEN];
int recv_len;
char src_ip[INET_ADDRSTRLEN];
unsigned short src_port;
int js_cb_ref;
} udp_recv_notify_param_t;
static char g_udp_close_flag = 0;
static char g_udp_recv_flag = 0;
static aos_sem_t g_udp_close_sem = NULL;
/*************************************************************************************
* Function: native_udp_create_socket
* 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 duk_ret_t native_udp_create_socket(duk_context *ctx)
{
int sock_id = 0;
sock_id = aos_udp_socket_create();
if (sock_id < 0) {
amp_warn(MOD_STR, "create socket error!");
goto out;
}
amp_debug(MOD_STR, "sock_id = %d", sock_id);
duk_push_int(ctx, sock_id);
return 1;
out:
duk_push_string(ctx, "create socket error!");
return duk_throw(ctx);
}
/*************************************************************************************
* Function: native_udp_bind
* Description: js native addon for UDP.bind(sock_id,"ip",port)
* Called by: js api
* Input: UDP.bind(sock_id,"ip",port):
* sock_id: is a iterger
* ip: is a ip stirng like "192.168.1.1"
* port: is a iterger port
* Output: return 0 when bind successed
* return error number when bind fail
**************************************************************************************/
static duk_ret_t native_udp_bind(duk_context *ctx)
{
int ret = -1;
int port = 0;
int sock_id;
if (!duk_is_number(ctx, 0) || !duk_is_number(ctx, 1)) {
amp_warn(MOD_STR, "parameter must be (number, number)");
goto out;
}
sock_id = duk_get_int(ctx, 0);
if (sock_id < 0) {
amp_error(MOD_STR, "socket id[%d] error", sock_id);
goto out;
}
port = duk_get_int(ctx, 1);
if (port < 0) {
amp_error(MOD_STR, "port[%d] error", port);
goto out;
}
amp_debug(MOD_STR, "udp bind socket id=%d, port=%d", sock_id, port);
ret = aos_udp_socket_bind(sock_id, port);
if (ret < 0) {
amp_error(MOD_STR, "udp bind error");
goto out;
}
// return ret;
out:
duk_push_int(ctx, ret);
return 1;
}
static void udp_send_notify(void *pdata)
{
udp_send_notify_param_t *p = (udp_send_notify_param_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx, p->js_cb_ref);
duk_push_int(ctx, p->ret);
if (duk_pcall(ctx, 1) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
be_unref(ctx, p->js_cb_ref);
aos_free(p);
duk_gc(ctx, 0);
}
/*************************************************************************************
* Function: udp_send_routin
* Description: create a task for blocking sendto call
* Called by:
**************************************************************************************/
static int udp_send_routine(udp_send_param_t *send_param)
{
int ret = -1;
int sock_id;
udp_options_t udp_options;
udp_send_notify_param_t *p;
duk_context *ctx = be_get_context();
sock_id = send_param->sock_id;
memcpy(&udp_options, &(send_param->options), sizeof(udp_options_t));
ret = aos_udp_sendto(sock_id, &udp_options, send_param->msg,
send_param->msg_len, 0);
p = aos_calloc(1, sizeof(udp_send_notify_param_t));
if (!p) {
amp_warn(MOD_STR, "allocate memory failed");
be_unref(ctx, send_param->js_cb_ref);
goto out;
}
p->js_cb_ref = send_param->js_cb_ref;
p->ret = ret;
py_task_schedule_call(udp_send_notify, p);
ret = 0;
out:
aos_free(send_param->msg);
aos_free(send_param);
return ret;
}
/*************************************************************************************
* Function: native_udp_sendto
* Description: js native addon for
*UDP.send(sock_id,option,buffer_array,function(ret){}) Called by: js api
* Input: sock_id: interger
* options: is a object include options.ip and options.port
* buffer_array: is a array which include message to send
* function(ret): is the callback function which has a ret input
*param Output: return send msg length when send success return error
*number when send fail
**************************************************************************************/
static duk_ret_t native_udp_sendto(duk_context *ctx)
{
int ret = -1;
udp_options_t options;
int sock_id;
int i;
int msg_len;
char *msg;
if (!duk_is_number(ctx, 0) || !duk_is_object(ctx, 1) ||
!duk_is_function(ctx, 2)) {
amp_warn(MOD_STR,
"parameter must be (number, object, array, function)");
goto out;
}
sock_id = duk_get_int(ctx, 0);
if (sock_id <= 0) {
amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id);
goto out;
}
memset(&options, 0, sizeof(udp_options_t));
/* options.port */
duk_get_prop_string(ctx, 1, "port");
if (!duk_is_number(ctx, -1)) {
amp_warn(MOD_STR, "port not specify");
duk_pop(ctx);
goto out;
}
options.port = duk_get_int(ctx, -1);
duk_pop(ctx);
/* options.address */
duk_get_prop_string(ctx, 1, "address");
if (!duk_is_string(ctx, -1)) {
amp_warn(MOD_STR, "ip not specify");
duk_pop(ctx);
goto out;
}
strncpy(options.ip, duk_get_string(ctx, -1), sizeof(options.ip) - 1);
duk_pop(ctx);
/* options.message */
duk_get_prop_string(ctx, 1, "message");
if (!duk_is_array(ctx, -1)) {
amp_warn(MOD_STR, "message not specify");
duk_pop(ctx);
goto out;
}
msg_len = duk_get_length(ctx, -1);
msg = (char *)aos_calloc(1, msg_len + 1);
if (!msg) {
amp_warn(MOD_STR, "allocate memory failed");
goto out;
}
for (i = 0; i < msg_len; i++) {
duk_get_prop_index(ctx, -1, i);
msg[i] = duk_get_int(ctx, -1);
duk_pop(ctx);
}
msg[msg_len] = 0;
// options.msg = (char *)duk_get_string(ctx, -1);
// msg_len = strlen(options.msg);
// duk_pop(ctx);
// msg = (char *)aos_calloc(1, msg_len + 1);
// if (!msg) {
// amp_warn(MOD_STR, "allocate memory failed");
// goto out;
// }
// strncpy(msg, options.msg, msg_len);
amp_debug(MOD_STR, "msg is:%s, length is: %d", msg, msg_len);
udp_send_param_t *send_param =
(udp_send_param_t *)aos_malloc(sizeof(*send_param));
if (!send_param) {
amp_error(MOD_STR, "allocate memory failed");
aos_free(msg);
goto out;
}
send_param->sock_id = sock_id;
duk_dup(ctx, 2);
send_param->js_cb_ref = be_ref(ctx);
send_param->msg = msg;
send_param->msg_len = msg_len;
memcpy(&(send_param->options), &options, sizeof(udp_options_t));
amp_debug(MOD_STR, "sockid:%d ip:%s port:%d msg:%s msg_len:%d", sock_id,
options.ip, options.port, msg, msg_len);
udp_send_routine(send_param);
out:
duk_push_int(ctx, ret);
return 1;
}
static void udp_recv_notify(void *pdata)
{
int i = 0;
udp_recv_notify_param_t *p = (udp_recv_notify_param_t *)pdata;
duk_context *ctx = be_get_context();
be_push_ref(ctx, p->js_cb_ref);
int arr_idx = duk_push_array(ctx);
if (p->recv_len > 0) {
for (i = 0; i < p->recv_len; i++) {
duk_push_int(ctx, p->buf[i]);
duk_put_prop_index(ctx, arr_idx, i);
}
}
duk_push_object(ctx);
duk_push_string(ctx, p->src_ip);
duk_put_prop_string(ctx, -2, "host");
duk_push_uint(ctx, p->src_port);
duk_put_prop_string(ctx, -2, "port");
duk_push_int(ctx, p->recv_len);
if (duk_pcall(ctx, 3) != DUK_EXEC_SUCCESS) {
amp_console("%s", duk_safe_to_stacktrace(ctx, -1));
}
duk_pop(ctx);
duk_gc(ctx, 0);
if (p->recv_len < 0) {
be_unref(ctx, p->js_cb_ref);
aos_free(p);
}
}
/*************************************************************************************
* Function: udp_recv_routine
* Description: create a task for blocking recvfrom call
* Called by:
**************************************************************************************/
static void udp_recv_routine(void *arg)
{
udp_recv_param_t *recv_param = (udp_recv_param_t *)arg;
int sock_id;
udp_options_t udp_options;
aos_networkAddr addr_info;
udp_recv_notify_param_t *p;
duk_context *ctx = be_get_context();
sock_id = recv_param->sock_id;
memcpy(&udp_options, &(recv_param->options), sizeof(udp_options_t));
p = aos_calloc(1, sizeof(udp_recv_notify_param_t));
if (!p) {
amp_warn(MOD_STR, "allocate memory failed");
duk_context *ctx = be_get_context();
be_unref(ctx, recv_param->js_cb_ref);
goto out;
}
g_udp_recv_flag = 1;
while (1) {
p->recv_len = aos_udp_recvfrom(sock_id, &addr_info, p->buf,
sizeof(p->buf), MAX_UDP_RECV_TIMEOUT);
strcpy(p->src_ip, addr_info.addr);
p->src_port = addr_info.port;
p->js_cb_ref = recv_param->js_cb_ref;
if (p->recv_len > 0) {
py_task_schedule_call(udp_recv_notify, p);
}
if (p->recv_len < 0) {
// connection closed
amp_error(MOD_STR, "connection closed:%d", p->recv_len);
break;
}
if (g_udp_close_flag) {
duk_context *ctx = be_get_context();
be_unref(ctx, recv_param->js_cb_ref);
if (p) {
aos_free(p);
}
break;
}
}
aos_udp_close_without_connect(sock_id);
out:
aos_free(recv_param);
g_udp_recv_flag = 0;
aos_sem_signal(&g_udp_close_sem);
aos_task_exit(0);
return;
}
/*************************************************************************************
* Function: native_udp_recvfrom
* Description: js native addon for
* UDP.recv(sock_id,function(length, buffer_array, src_ip,
*src_port){}) Called by: js api Input: sock_id: interger
* function(length, buffer_array, src_ip, src_port): the callback
*function length: the recv msg length buffer_array: the recv msg buffer src_ip:
*the peer ip string src_port: the peer port which is a interger
*
* Output: return 0 when UDP.recv call ok
* return error number UDP.recv call fail
**************************************************************************************/
static duk_ret_t native_udp_recvfrom(duk_context *ctx)
{
int ret = -1;
int sock_id = 0;
aos_task_t udp_recv_task;
udp_recv_param_t *recv_param;
if (!duk_is_number(ctx, 0) || !duk_is_function(ctx, 1)) {
amp_warn(MOD_STR, "parameter must be number and function");
goto out;
}
sock_id = duk_get_int(ctx, 0);
if (sock_id < 0) {
amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id);
goto out;
}
amp_debug(MOD_STR, "sock_id: %d", sock_id);
recv_param = (udp_recv_param_t *)aos_calloc(1, sizeof(*recv_param));
if (!recv_param) {
amp_warn(MOD_STR, "allocate memory failed");
goto out;
}
recv_param->sock_id = sock_id;
duk_dup(ctx, 1);
recv_param->js_cb_ref = be_ref(ctx);
ret =
aos_task_new_ext(&udp_recv_task, "amp udp recv task", udp_recv_routine,
recv_param, 1024 * 4, ADDON_TSK_PRIORRITY);
if (ret != 0) {
amp_debug(MOD_STR, "udp recv task create faild");
goto out;
}
out:
duk_push_int(ctx, ret);
return 1;
}
/*************************************************************************************
* Function: native_udp_close_socket
* 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 duk_ret_t native_udp_close_socket(duk_context *ctx)
{
int ret = -1;
int sock_id = 0;
if (!duk_is_number(ctx, 0)) {
amp_warn(MOD_STR, "parameter must be number");
goto out;
}
sock_id = duk_get_int(ctx, 0);
if (sock_id <= 0) {
amp_warn(MOD_STR, "socket id[%d] is invalid", sock_id);
goto out;
}
g_udp_close_flag = 1;
aos_sem_wait(&g_udp_close_sem, MAX_UDP_RECV_TIMEOUT + 50);
g_udp_close_flag = 0;
ret = 0;
out:
duk_push_int(ctx, ret);
return 1;
}
static void module_udp_source_clean(void)
{
if (g_udp_recv_flag) {
g_udp_close_flag = 1;
aos_sem_wait(&g_udp_close_sem, MAX_UDP_RECV_TIMEOUT + 50);
g_udp_close_flag = 0;
}
}
void module_udp_register(void)
{
duk_context *ctx = be_get_context();
if (!g_udp_close_sem) {
if (aos_sem_new(&g_udp_close_sem, 0) != 0) {
amp_error(MOD_STR, "create udp sem fail");
return;
}
}
amp_module_free_register(module_udp_source_clean);
duk_push_object(ctx);
AMP_ADD_FUNCTION("createSocket", native_udp_create_socket, 0);
AMP_ADD_FUNCTION("bind", native_udp_bind, 2);
AMP_ADD_FUNCTION("sendto", native_udp_sendto, 3);
AMP_ADD_FUNCTION("recvfrom", native_udp_recvfrom, 2);
AMP_ADD_FUNCTION("close", native_udp_close_socket, 1);
duk_put_prop_string(ctx, -2, "UDP");
}
| YifuLiu/AliOS-Things | components/py_engine/modules/network/udp/module_udp.c | C | apache-2.0 | 14,625 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <stdarg.h>
#include <string.h>
#if MICROPY_PY_CHANNEL_ENABLE
#include "board_config.h"
#include "py/builtin.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "py_defines.h"
#define MOD_STR "ONLINE_UPGRADE"
extern int check_channel_enable(void);
static mp_obj_t online_upgradde_trigger = MP_OBJ_NULL;
int on_get_url(char *url)
{
callback_to_python_LoBo(online_upgradde_trigger, mp_obj_new_str(url, strlen(url)), NULL);
return 0 ;
}
STATIC mp_obj_t online_channel_register_cb(mp_obj_t func)
{
// if (check_channel_enable() == 0)
// amp_otaput_init(on_get_url);
online_upgradde_trigger = func;
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_channel_register_cb, online_channel_register_cb);
STATIC const mp_rom_map_elem_t online_upgrade_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_online_upgrade) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_on), MP_ROM_PTR(&native_channel_register_cb) },
};
STATIC MP_DEFINE_CONST_DICT(online_upgrade_module_globals, online_upgrade_module_globals_table);
const mp_obj_module_t mp_module_online_upgrade = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&online_upgrade_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_online_upgrade, mp_module_online_upgrade, MICROPY_PY_CHANNEL_ENABLE);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/online_upgrade/modonline_upgrade.c | C | apache-2.0 | 1,434 |
#include "aliot_base64.h"
#include <stdint.h>
#include <stdlib.h>
static int8_t g_encodingTable[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
static int8_t g_decodingTable[256];
static int32_t g_modTable[] = { 0, 2, 1 };
static void build_decoding_table(void)
{
static int32_t signal = 0;
int32_t i = 0;
if (signal != 0) {
return;
}
for (i = 0; i < 64; i++) {
g_decodingTable[(uint8_t)g_encodingTable[i]] = i;
}
signal = 1;
return;
}
int32_t aliot_base64encode(const uint8_t *data, uint32_t inputLength, uint32_t outputLenMax, uint8_t *encodedData,
uint32_t *outputLength)
{
uint32_t i = 0;
uint32_t j = 0;
if (NULL == encodedData) {
// ALIOT_LOG_ERROR("pointer of encodedData is NULL!");
return -1;
}
*outputLength = 4 * ((inputLength + 2) / 3);
if (outputLenMax < *outputLength) {
// ALIOT_LOG_ERROR("the length of output memory is not enough!");
return -1;
}
for (i = 0, j = 0; i < inputLength;) {
uint32_t octet_a = i < inputLength ? (uint8_t)data[i++] : 0;
uint32_t octet_b = i < inputLength ? (uint8_t)data[i++] : 0;
uint32_t octet_c = i < inputLength ? (uint8_t)data[i++] : 0;
uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;
encodedData[j++] = g_encodingTable[(triple >> 3 * 6) & 0x3F];
encodedData[j++] = g_encodingTable[(triple >> 2 * 6) & 0x3F];
encodedData[j++] = g_encodingTable[(triple >> 1 * 6) & 0x3F];
encodedData[j++] = g_encodingTable[(triple >> 0 * 6) & 0x3F];
}
for (i = 0; i < g_modTable[inputLength % 3]; i++) {
encodedData[*outputLength - 1 - i] = '=';
}
return 0;
}
int32_t aliot_base64decode(const uint8_t *data, uint32_t inputLength, uint32_t outputLenMax, uint8_t *decodedData,
uint32_t *outputLength)
{
uint32_t i = 0;
uint32_t j = 0;
build_decoding_table();
if (inputLength % 4 != 0) {
// ALIOT_LOG_ERROR("the input length is error!");
return -1;
}
*outputLength = inputLength / 4 * 3;
if (data[inputLength - 1] == '=') {
(*outputLength)--;
}
if (data[inputLength - 2] == '=') {
(*outputLength)--;
}
if (outputLenMax < *outputLength) {
// ALIOT_LOG_ERROR("the length of output memory is not enough!");
return -1;
}
uint32_t sextet_a = 0;
uint32_t sextet_b = 0;
uint32_t sextet_c = 0;
uint32_t sextet_d = 0;
uint32_t triple = 0;
for (i = 0, j = 0; i < inputLength;) {
sextet_a = data[i] == '=' ? 0 & i++ : g_decodingTable[data[i++]];
sextet_b = data[i] == '=' ? 0 & i++ : g_decodingTable[data[i++]];
sextet_c = data[i] == '=' ? 0 & i++ : g_decodingTable[data[i++]];
sextet_d = data[i] == '=' ? 0 & i++ : g_decodingTable[data[i++]];
triple = (sextet_a << 3 * 6) + (sextet_b << 2 * 6) + (sextet_c << 1 * 6) + (sextet_d << 0 * 6);
if (j < *outputLength) {
decodedData[j++] = (triple >> 2 * 8) & 0xFF;
}
if (j < *outputLength) {
decodedData[j++] = (triple >> 1 * 8) & 0xFF;
}
if (j < *outputLength) {
decodedData[j++] = (triple >> 0 * 8) & 0xFF;
}
}
return 0;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_base64.c | C | apache-2.0 | 3,760 |
#ifndef _ALIOT_COMMON_BASE64_H_
#define _ALIOT_COMMON_BASE64_H_
#include <stdint.h>
int32_t aliot_base64encode(const uint8_t *data, uint32_t inputLength, uint32_t outputLenMax, uint8_t *encodedData,
uint32_t *outputLength);
int32_t aliot_base64decode(const uint8_t *data, uint32_t inputLength, uint32_t outputLenMax, uint8_t *decodedData,
uint32_t *outputLength);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_base64.h | C | apache-2.0 | 431 |
#include "aliot_hmac.h"
#include <string.h>
#include "aliot_sha1.h"
#define KEY_IOPAD_SIZE (64)
#define SHA1_DIGEST_SIZE (20)
void aliot_hmac_sha1(const char *msg, int msg_len, char *digest, const char *key, int key_len)
{
iot_sha1_context context;
unsigned char k_ipad[KEY_IOPAD_SIZE]; /* inner padding - key XORd with ipad */
unsigned char k_opad[KEY_IOPAD_SIZE]; /* outer padding - key XORd with opad */
unsigned char out[SHA1_DIGEST_SIZE];
int i;
/* start out by storing key in pads */
memset(k_ipad, 0, sizeof(k_ipad));
memset(k_opad, 0, sizeof(k_opad));
memcpy(k_ipad, key, key_len);
memcpy(k_opad, key, key_len);
/* XOR key with ipad and opad values */
for (i = 0; i < KEY_IOPAD_SIZE; i++) {
k_ipad[i] ^= 0x36;
k_opad[i] ^= 0x5c;
}
/* perform inner SHA */
aliot_sha1_init(&context); /* init context for 1st pass */
aliot_sha1_starts(&context); /* setup context for 1st pass */
aliot_sha1_update(&context, k_ipad, KEY_IOPAD_SIZE); /* start with inner pad */
aliot_sha1_update(&context, (unsigned char *)msg, msg_len); /* then text of datagram */
aliot_sha1_finish(&context, out); /* finish up 1st pass */
/* perform outer SHA */
aliot_sha1_init(&context); /* init context for 2nd pass */
aliot_sha1_starts(&context); /* setup context for 2nd pass */
aliot_sha1_update(&context, k_opad, KEY_IOPAD_SIZE); /* start with outer pad */
aliot_sha1_update(&context, out, SHA1_DIGEST_SIZE); /* then results of 1st hash */
aliot_sha1_finish(&context, out); /* finish up 2nd pass */
memcpy(digest, out, SHA1_DIGEST_SIZE);
/*
for (i = 0; i < SHA1_DIGEST_SIZE; ++i) {
digest[i * 2] = aliot_hb2hex(out[i] >> 4);
digest[i * 2 + 1] = aliot_hb2hex(out[i]);
}
*/
}
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_hmac.c | C | apache-2.0 | 1,985 |
#ifndef _ALIOT_COMMON_HMAC_H_
#define _ALIOT_COMMON_HMAC_H_
#include <string.h>
void aliot_hmac_md5(const char *msg, int msg_len, char *digest, const char *key, int key_len);
void aliot_hmac_sha1(const char *msg, int msg_len, char *digest, const char *key, int key_len);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_hmac.h | C | apache-2.0 | 283 |
#include "aliot_httpapi_oss.h"
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "py/mperrno.h"
#include "shared/timeutils/timeutils.h"
#define TAG "OSS_HTTP"
#define CRLF "\r\n"
/* 获取星期 */
const char *getWeekdayByYearday(int32_t iY, int32_t iM, int32_t iD)
{
int32_t iWeekDay = -1;
if (1 == iM || 2 == iM) {
iM += 12;
iY--;
}
iWeekDay = (iD + 1 + 2 * iM + 3 * (iM + 1) / 5 + iY + iY / 4 - iY / 100 + iY / 400) % 7;
switch (iWeekDay) {
case 0:
return "Sun";
case 1:
return "Mon";
case 2:
return "Tue";
case 3:
return "Wed";
case 4:
return "Thu";
case 5:
return "Fri";
case 6:
return "Sat";
default:
return NULL;
}
return NULL;
}
/* 获取月份 */
const char *getMothStr(int32_t moth)
{
switch (moth) {
case 1:
return "Jan";
case 2:
return "Feb";
case 3:
return "Mar";
case 4:
return "Apr";
case 5:
return "May";
case 6:
return "Jun";
case 7:
return "Jul";
case 8:
return "Aug";
case 9:
return "Sep";
case 10:
return "Oct";
case 11:
return "Nov";
case 12:
return "Dec";
default:
return NULL;
}
}
static int32_t httpclient_put_file(httpclient_t *client, const char *url, const char *localPath,
httpclient_data_t *client_data)
{
int32_t ret = 0;
uint8_t buf[MAX_HTTP_OUTPUT_BUFFER] = { 0 };
if (NULL == client || NULL == url || NULL == localPath || NULL == client_data) {
LOGE(TAG, "params null");
return -EINVAL;
}
FILE *fd = fopen(localPath, "r");
if (fd == NULL) {
LOGE(TAG, "failed to open file:%s", localPath);
return -ENOENT;
}
ret = httpclient_conn(client, url);
if (ret == HTTP_SUCCESS) {
ret = httpclient_send(client, url, HTTP_PUT, client_data);
if (ret == HTTP_SUCCESS) {
do {
int32_t read_size = fread(buf, 1, sizeof(buf), fd);
if (read_size > 0) {
// pass do nothing
} else if (read_size < 0) {
// if num < 0 read file eror
ret = read_size;
goto exit;
} else if (read_size == 0) {
// if num == 0 read file eof
fclose(fd);
fd = NULL;
break;
}
ret = http_tcp_send_wrapper(client, buf, read_size);
if (ret < 0) {
goto exit;
}
} while (1);
ret = httpclient_recv(client, client_data);
}
}
exit:
if (fd != NULL) {
fclose(fd);
}
httpclient_clse(client);
return ret;
}
static int32_t httpclient_put_content(httpclient_t *client, const char *url, const char *content_data,
httpclient_data_t *client_data)
{
int32_t ret = 0;
int32_t num = 0;
if (NULL == client || NULL == url || NULL == content_data || NULL == client_data) {
return -EINVAL;
}
ret = httpclient_conn(client, url);
if (ret == HTTP_SUCCESS) {
ret = httpclient_send(client, url, HTTP_PUT, client_data);
if (ret == HTTP_SUCCESS) {
num = strlen(content_data) + 2;
ret = http_tcp_send_wrapper(client, content_data, num);
if (ret < 0) {
goto exit;
}
ret = httpclient_recv(client, client_data);
}
}
exit:
httpclient_clse(client);
return ret;
}
static int32_t httpclient_get_file(httpclient_t *client, const char *url, const char *localPath,
httpclient_data_t *client_data)
{
int32_t num = 0;
int32_t ret;
FILE *fd = fopen(localPath, "w+");
if (fd == 0) {
return -EPERM;
}
ret = httpclient_conn(client, url);
if (ret == HTTP_SUCCESS) {
ret = httpclient_send(client, url, HTTP_GET, client_data);
if (ret != HTTP_SUCCESS) {
goto exit;
}
do {
ret = httpclient_recv(client, client_data);
if (ret < 0) {
goto exit;
}
num = fwrite(client_data->response_buf, 1, client_data->content_block_len, fd);
if (num <= 0) {
ret = num;
goto exit;
}
} while (client_data->is_more);
}
exit:
if (fd != NULL) {
fclose(fd);
}
httpclient_clse(client);
return ret;
}
int32_t oss_http_put_object(const char *key, const char *secret, const char *endPoint, const char *BucketName,
const char *ObjectName, const char *LocalPath, char *resbuf, uint32_t reslen)
{
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
char url[256] = { 0 };
char puthead[256] = { 0 };
char signmsg[128] = { 0 };
int32_t ret = 0;
char signbin[64] = { 0 };
char sign[64] = { 0 };
uint32_t outputLength = 0;
long LocalfileSize = 0;
struct stat tmpstat = { 0 };
/* 获取时间 */
struct timeval tv = { 0 };
timeutils_struct_time_t datetime = { 0 };
gettimeofday(&tv, NULL);
timeutils_seconds_since_epoch_to_struct_time(tv.tv_sec, &datetime);
const char *gmtweek = getWeekdayByYearday(datetime.tm_year, datetime.tm_mon, datetime.tm_mday);
const char *gmtmon = getMothStr(datetime.tm_mon);
/* 签名认证组包 */
sprintf(signmsg, "PUT\n\ntext/plain\n%s, %02ld %s %04ld %02ld:%02ld:%02ld GMT\n/%s/%s", gmtweek,
(long)datetime.tm_mday, gmtmon, (long)datetime.tm_year, (long)datetime.tm_hour, (long)datetime.tm_min,
(long)datetime.tm_sec, BucketName, ObjectName);
LOGD(TAG, "signmsg:%s\r\n", signmsg);
/* 签名认证 */
aliot_hmac_sha1(signmsg, strlen(signmsg), signbin, secret, strlen(secret));
/* 签名认证之后的base64数据格式转换 */
aliot_base64encode((const uint8_t *)signbin, strlen(signbin), sizeof(sign), (uint8_t *)sign,
&outputLength); // mod by wy 210428(sign类型不匹配)
LOGD(TAG, "sign:%s\r\n", sign);
/* 组合url */
sprintf(url, "http://%s.%s/%s", BucketName, endPoint, ObjectName);
LOGD(TAG, "url:%s\r\n", url);
ret = stat(LocalPath, &tmpstat);
if (ret < 0) {
return -1;
}
LocalfileSize = tmpstat.st_size + 2;
/* 请求头组包 */
sprintf(puthead,
"Authorization: OSS %s:%s" CRLF "Date: %s, %02ld %s %04ld %02ld:%02ld:%02ld GMT" CRLF
"Content-Type: text/plain" CRLF "Content-Length: %ld" CRLF CRLF,
key, sign, gmtweek, (long)datetime.tm_mday, gmtmon, (long)datetime.tm_year, (long)datetime.tm_hour,
(long)datetime.tm_min, (long)datetime.tm_sec, LocalfileSize); // mod by wy 210428(%2d-->%2ld)
LOGD(TAG, "puthead:%s\r\n", puthead);
client.header = puthead;
client_data.response_buf = resbuf;
client_data.response_buf_len = reslen;
client_data.header_buf = resbuf;
client_data.header_buf_len = reslen;
/* 获取文件并PUT请求连接HTTP服务器 */
ret = (int32_t)httpclient_put_file(&client, url, LocalPath, &client_data);
return ret;
}
int32_t oss_http_get_object(const char *key, const char *secret, const char *endPoint, const char *BucketName,
const char *ObjectName, const char *LocalPath, char *range, char *resbuf, uint32_t reslen)
{
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
char url[256] = { 0 };
char gethead[258] = { 0 };
char signmsg[128] = { 0 };
int32_t ret = 0;
char signbin[128] = { 0 };
char sign[64] = { 0 };
uint32_t outputLength = 0;
/* 获取当前时间 */
struct timeval tv = { 0 };
timeutils_struct_time_t datetime = { 0 };
gettimeofday(&tv, NULL);
timeutils_seconds_since_epoch_to_struct_time(tv.tv_sec, &datetime);
const char *gmtweek = getWeekdayByYearday(datetime.tm_year, datetime.tm_mon, datetime.tm_mday);
const char *gmtmon = getMothStr(datetime.tm_mon);
/* 签名认证组包 */
sprintf(signmsg, "GET\n\n\n%s, %02ld %s %04ld %02ld:%02ld:%02ld GMT\n/%s/%s", gmtweek, (long)datetime.tm_mday,
gmtmon, (long)datetime.tm_year, (long)datetime.tm_hour, (long)datetime.tm_min, (long)datetime.tm_sec,
BucketName, ObjectName);
LOGD(TAG, "signmsg:%s\r\n", signmsg);
/* 签名认证 */
aliot_hmac_sha1(signmsg, strlen(signmsg), signbin, secret, strlen(secret));
/* 签名认证之后的base64数据格式转换 */
aliot_base64encode((const uint8_t *)signbin, strlen(signbin), sizeof(sign), (uint8_t *)sign,
&outputLength); // mod by wy 210428 (类型不匹配)
LOGD(TAG, "sign:%s\r\n", sign);
/* 组合url */
sprintf(url, "http://%s.%s/%s", BucketName, endPoint, ObjectName);
LOGD(TAG, "url:%s\r\n", url);
/* 请求头组包 */
if (range == NULL) {
sprintf(gethead, "Authorization: OSS %s:%s" CRLF "Date: %s, %02ld %s %04ld %02ld:%02ld:%02ld GMT" CRLF CRLF,
key, sign, gmtweek, (long)datetime.tm_mday, gmtmon, (long)datetime.tm_year, (long)datetime.tm_hour,
(long)datetime.tm_min, (long)datetime.tm_sec);
} else {
sprintf(gethead,
"Authorization: OSS %s:%s" CRLF "Date: %s, %02ld %s %04ld %02ld:%02ld:%02ld GMT" CRLF
"Range: bytes=%s" CRLF CRLF,
key, sign, gmtweek, (long)datetime.tm_mday, gmtmon, (long)datetime.tm_year, (long)datetime.tm_hour,
(long)datetime.tm_min, (long)datetime.tm_sec, range); // mod by wy 210428(%2d-->%2ld)
}
LOGD(TAG, "gethead:%s\r\n", gethead);
client.header = gethead;
client_data.response_buf = resbuf;
client_data.response_buf_len = reslen;
client_data.header_buf = resbuf;
client_data.header_buf_len = reslen;
/* 获取文件并GET请求连接HTTP服务器 */
ret = httpclient_get_file(&client, url, LocalPath, &client_data);
return ret;
}
int32_t oss_http_put_content(const char *key, const char *secret, const char *endPoint, const char *BucketName,
const char *ObjectName, const char *ContentData, char *resbuf, uint32_t reslen)
{
httpclient_t client = { 0 };
httpclient_data_t client_data = { 0 };
char url[256] = { 0 };
char puthead[256] = { 0 };
char signmsg[128] = { 0 };
int32_t ret = 0;
char signbin[64] = { 0 };
char sign[64] = { 0 };
uint32_t outputLength = 0;
long LocalfileSize = 0;
/* 获取时间 */
struct timeval tv = { 0 };
timeutils_struct_time_t datetime = { 0 };
gettimeofday(&tv, NULL);
timeutils_seconds_since_epoch_to_struct_time(tv.tv_sec, &datetime);
const char *gmtweek = getWeekdayByYearday(datetime.tm_year, datetime.tm_mon, datetime.tm_mday);
const char *gmtmon = getMothStr(datetime.tm_mon);
/* 签名认证组包 */
sprintf(signmsg, "PUT\n\ntext/plain\n%s, %02ld %s %04ld %02ld:%02ld:%02ld GMT\n/%s/%s", gmtweek,
(long)datetime.tm_mday, gmtmon, (long)datetime.tm_year, (long)datetime.tm_hour, (long)datetime.tm_min,
(long)datetime.tm_sec, BucketName, ObjectName);
LOGD(TAG, "signmsg:%s\r\n", signmsg);
/* 签名认证 */
aliot_hmac_sha1(signmsg, strlen(signmsg), signbin, secret, strlen(secret));
/* 签名认证之后的base64数据格式转换 */
aliot_base64encode((const uint8_t *)signbin, strlen(signbin), sizeof(sign), (uint8_t *)sign,
&outputLength); // mod by wy 210428(sign类型不匹配)
LOGD(TAG, "sign:%s\r\n", sign);
/* 组合url */
sprintf(url, "http://%s.%s/%s", BucketName, endPoint, ObjectName);
LOGD(TAG, "url:%s\r\n", url);
LocalfileSize = strlen(ContentData) + 2;
/* 请求头组包 */
sprintf(puthead,
"Authorization: OSS %s:%s" CRLF "Date: %s, %02ld %s %04ld %02ld:%02ld:%02ld GMT" CRLF
"Content-Type: text/plain" CRLF "Content-Length: %ld" CRLF CRLF,
key, sign, gmtweek, (long)datetime.tm_mday, gmtmon, (long)datetime.tm_year, (long)datetime.tm_hour,
(long)datetime.tm_min, (long)datetime.tm_sec, LocalfileSize); // mod by wy 210428(%2d-->%2ld)
LOGD(TAG, "puthead:%s\r\n", puthead);
client.header = puthead;
client_data.response_buf = resbuf;
client_data.response_buf_len = reslen;
client_data.header_buf = resbuf;
client_data.header_buf_len = reslen;
/* 获取文件并PUT请求连接HTTP服务器 */
ret = (int32_t)httpclient_put_content(&client, url, ContentData, &client_data);
return ret;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_httpapi_oss.c | C | apache-2.0 | 12,954 |
#ifndef __ALIOT_HTTPAPI_OSS_H__
#define __ALIOT_HTTPAPI_OSS_H__
#include "aliot_base64.h"
#include "aliot_hmac.h"
#include "aliot_sha1.h"
#include "httpclient.h"
#include "ulog/ulog.h"
#define MAX_HTTP_OUTPUT_BUFFER (1024)
typedef struct {
char gmtweek[8];
char gmtmon[8];
} GmtTime_t;
typedef struct {
int32_t year;
int32_t month;
int32_t day;
int32_t hour;
int32_t minute;
int32_t second;
int32_t timezone; // one digit expresses a quarter of an hour, for example: 22 indicates "+5:30"
} ZYF_Time_t;
int32_t oss_http_get_object(const char *key, const char *secret, const char *endpoint, const char *bucketname,
const char *objectname, const char *localpath, char *range, char *resbuf, uint32_t reslen);
int32_t oss_http_put_object(const char *key, const char *secret, const char *endpoint, const char *bucketname,
const char *objectname, const char *localpath, char *resbuf, uint32_t reslen);
int32_t oss_http_put_content(const char *key, const char *secret, const char *endpoint, const char *bucketname,
const char *objectname, const char *ContentData, char *resbuf, uint32_t reslen);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_httpapi_oss.h | C | apache-2.0 | 1,225 |
#include "aliot_sha1.h"
#include <stdlib.h>
#include <string.h>
/* Implementation that should never be optimized out by the compiler */
static void aliot_sha1_zeroize(void *v, size_t n)
{
unsigned char *p = v;
while (n--) {
*p++ = 0;
}
}
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef IOT_SHA1_GET_UINT32_BE
#define IOT_SHA1_GET_UINT32_BE(n, b, i) \
{ \
(n) = ((uint32_t)(b)[(i)] << 24) | ((uint32_t)(b)[(i) + 1] << 16) | ((uint32_t)(b)[(i) + 2] << 8) | \
((uint32_t)(b)[(i) + 3]); \
}
#endif
#ifndef IOT_SHA1_PUT_UINT32_BE
#define IOT_SHA1_PUT_UINT32_BE(n, b, i) \
{ \
(b)[(i)] = (unsigned char)((n) >> 24); \
(b)[(i) + 1] = (unsigned char)((n) >> 16); \
(b)[(i) + 2] = (unsigned char)((n) >> 8); \
(b)[(i) + 3] = (unsigned char)((n)); \
}
#endif
void aliot_sha1_init(iot_sha1_context *ctx)
{
memset(ctx, 0, sizeof(iot_sha1_context));
}
void aliot_sha1_free(iot_sha1_context *ctx)
{
if (ctx == NULL) {
return;
}
aliot_sha1_zeroize(ctx, sizeof(iot_sha1_context));
}
void aliot_sha1_clone(iot_sha1_context *dst, const iot_sha1_context *src)
{
*dst = *src;
}
/*
* SHA-1 context setup
*/
void aliot_sha1_starts(iot_sha1_context *ctx)
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xC3D2E1F0;
}
void aliot_sha1_process(iot_sha1_context *ctx, const unsigned char data[64])
{
uint32_t temp, W[16], A, B, C, D, E;
IOT_SHA1_GET_UINT32_BE(W[0], data, 0);
IOT_SHA1_GET_UINT32_BE(W[1], data, 4);
IOT_SHA1_GET_UINT32_BE(W[2], data, 8);
IOT_SHA1_GET_UINT32_BE(W[3], data, 12);
IOT_SHA1_GET_UINT32_BE(W[4], data, 16);
IOT_SHA1_GET_UINT32_BE(W[5], data, 20);
IOT_SHA1_GET_UINT32_BE(W[6], data, 24);
IOT_SHA1_GET_UINT32_BE(W[7], data, 28);
IOT_SHA1_GET_UINT32_BE(W[8], data, 32);
IOT_SHA1_GET_UINT32_BE(W[9], data, 36);
IOT_SHA1_GET_UINT32_BE(W[10], data, 40);
IOT_SHA1_GET_UINT32_BE(W[11], data, 44);
IOT_SHA1_GET_UINT32_BE(W[12], data, 48);
IOT_SHA1_GET_UINT32_BE(W[13], data, 52);
IOT_SHA1_GET_UINT32_BE(W[14], data, 56);
IOT_SHA1_GET_UINT32_BE(W[15], data, 60);
#define S(x, n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
#define R(t) \
(temp = W[(t - 3) & 0x0F] ^ W[(t - 8) & 0x0F] ^ W[(t - 14) & 0x0F] ^ W[t & 0x0F], (W[t & 0x0F] = S(temp, 1)))
#define P(a, b, c, d, e, x) \
{ \
e += S(a, 5) + F(b, c, d) + K + x; \
b = S(b, 30); \
}
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
E = ctx->state[4];
#define F(x, y, z) (z ^ (x & (y ^ z)))
#define K 0x5A827999
P(A, B, C, D, E, W[0]);
P(E, A, B, C, D, W[1]);
P(D, E, A, B, C, W[2]);
P(C, D, E, A, B, W[3]);
P(B, C, D, E, A, W[4]);
P(A, B, C, D, E, W[5]);
P(E, A, B, C, D, W[6]);
P(D, E, A, B, C, W[7]);
P(C, D, E, A, B, W[8]);
P(B, C, D, E, A, W[9]);
P(A, B, C, D, E, W[10]);
P(E, A, B, C, D, W[11]);
P(D, E, A, B, C, W[12]);
P(C, D, E, A, B, W[13]);
P(B, C, D, E, A, W[14]);
P(A, B, C, D, E, W[15]);
P(E, A, B, C, D, R(16));
P(D, E, A, B, C, R(17));
P(C, D, E, A, B, R(18));
P(B, C, D, E, A, R(19));
#undef K
#undef F
#define F(x, y, z) (x ^ y ^ z)
#define K 0x6ED9EBA1
P(A, B, C, D, E, R(20));
P(E, A, B, C, D, R(21));
P(D, E, A, B, C, R(22));
P(C, D, E, A, B, R(23));
P(B, C, D, E, A, R(24));
P(A, B, C, D, E, R(25));
P(E, A, B, C, D, R(26));
P(D, E, A, B, C, R(27));
P(C, D, E, A, B, R(28));
P(B, C, D, E, A, R(29));
P(A, B, C, D, E, R(30));
P(E, A, B, C, D, R(31));
P(D, E, A, B, C, R(32));
P(C, D, E, A, B, R(33));
P(B, C, D, E, A, R(34));
P(A, B, C, D, E, R(35));
P(E, A, B, C, D, R(36));
P(D, E, A, B, C, R(37));
P(C, D, E, A, B, R(38));
P(B, C, D, E, A, R(39));
#undef K
#undef F
#define F(x, y, z) ((x & y) | (z & (x | y)))
#define K 0x8F1BBCDC
P(A, B, C, D, E, R(40));
P(E, A, B, C, D, R(41));
P(D, E, A, B, C, R(42));
P(C, D, E, A, B, R(43));
P(B, C, D, E, A, R(44));
P(A, B, C, D, E, R(45));
P(E, A, B, C, D, R(46));
P(D, E, A, B, C, R(47));
P(C, D, E, A, B, R(48));
P(B, C, D, E, A, R(49));
P(A, B, C, D, E, R(50));
P(E, A, B, C, D, R(51));
P(D, E, A, B, C, R(52));
P(C, D, E, A, B, R(53));
P(B, C, D, E, A, R(54));
P(A, B, C, D, E, R(55));
P(E, A, B, C, D, R(56));
P(D, E, A, B, C, R(57));
P(C, D, E, A, B, R(58));
P(B, C, D, E, A, R(59));
#undef K
#undef F
#define F(x, y, z) (x ^ y ^ z)
#define K 0xCA62C1D6
P(A, B, C, D, E, R(60));
P(E, A, B, C, D, R(61));
P(D, E, A, B, C, R(62));
P(C, D, E, A, B, R(63));
P(B, C, D, E, A, R(64));
P(A, B, C, D, E, R(65));
P(E, A, B, C, D, R(66));
P(D, E, A, B, C, R(67));
P(C, D, E, A, B, R(68));
P(B, C, D, E, A, R(69));
P(A, B, C, D, E, R(70));
P(E, A, B, C, D, R(71));
P(D, E, A, B, C, R(72));
P(C, D, E, A, B, R(73));
P(B, C, D, E, A, R(74));
P(A, B, C, D, E, R(75));
P(E, A, B, C, D, R(76));
P(D, E, A, B, C, R(77));
P(C, D, E, A, B, R(78));
P(B, C, D, E, A, R(79));
#undef K
#undef F
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
ctx->state[4] += E;
}
/*
* SHA-1 process buffer
*/
void aliot_sha1_update(iot_sha1_context *ctx, const unsigned char *input, size_t ilen)
{
size_t fill;
uint32_t left;
if (ilen == 0) {
return;
}
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += (uint32_t)ilen;
ctx->total[0] &= 0xFFFFFFFF;
if (ctx->total[0] < (uint32_t)ilen) {
ctx->total[1]++;
}
if (left && ilen >= fill) {
memcpy((void *)(ctx->buffer + left), input, fill);
aliot_sha1_process(ctx, ctx->buffer);
input += fill;
ilen -= fill;
left = 0;
}
while (ilen >= 64) {
aliot_sha1_process(ctx, input);
input += 64;
ilen -= 64;
}
if (ilen > 0) {
memcpy((void *)(ctx->buffer + left), input, ilen);
}
}
static const unsigned char iot_sha1_padding[64] = { 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
/*
* SHA-1 final digest
*/
void aliot_sha1_finish(iot_sha1_context *ctx, unsigned char output[20])
{
uint32_t last, padn;
uint32_t high, low;
unsigned char msglen[8];
high = (ctx->total[0] >> 29) | (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
IOT_SHA1_PUT_UINT32_BE(high, msglen, 0);
IOT_SHA1_PUT_UINT32_BE(low, msglen, 4);
last = ctx->total[0] & 0x3F;
padn = (last < 56) ? (56 - last) : (120 - last);
aliot_sha1_update(ctx, iot_sha1_padding, padn);
aliot_sha1_update(ctx, msglen, 8);
IOT_SHA1_PUT_UINT32_BE(ctx->state[0], output, 0);
IOT_SHA1_PUT_UINT32_BE(ctx->state[1], output, 4);
IOT_SHA1_PUT_UINT32_BE(ctx->state[2], output, 8);
IOT_SHA1_PUT_UINT32_BE(ctx->state[3], output, 12);
IOT_SHA1_PUT_UINT32_BE(ctx->state[4], output, 16);
}
/*
* output = SHA-1( input buffer )
*/
void aliot_sha1(const unsigned char *input, size_t ilen, unsigned char output[20])
{
iot_sha1_context ctx;
aliot_sha1_init(&ctx);
aliot_sha1_starts(&ctx);
aliot_sha1_update(&ctx, input, ilen);
aliot_sha1_finish(&ctx, output);
aliot_sha1_free(&ctx);
}
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_sha1.c | C | apache-2.0 | 8,206 |
#ifndef _ALIOT_COMMON_SHA1_H_
#define _ALIOT_COMMON_SHA1_H_
#include <stdint.h>
#include <stddef.h>
/**
* \brief SHA-1 context structure
*/
typedef struct {
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[5]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
} iot_sha1_context;
/**
* \brief Initialize SHA-1 context
*
* \param ctx SHA-1 context to be initialized
*/
void aliot_sha1_init(iot_sha1_context *ctx);
/**
* \brief Clear SHA-1 context
*
* \param ctx SHA-1 context to be cleared
*/
void aliot_sha1_free(iot_sha1_context *ctx);
/**
* \brief Clone (the state of) a SHA-1 context
*
* \param dst The destination context
* \param src The context to be cloned
*/
void aliot_sha1_clone(iot_sha1_context *dst, const iot_sha1_context *src);
/**
* \brief SHA-1 context setup
*
* \param ctx context to be initialized
*/
void aliot_sha1_starts(iot_sha1_context *ctx);
/**
* \brief SHA-1 process buffer
*
* \param ctx SHA-1 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void aliot_sha1_update(iot_sha1_context *ctx, const unsigned char *input, size_t ilen);
/**
* \brief SHA-1 final digest
*
* \param ctx SHA-1 context
* \param output SHA-1 checksum result
*/
void aliot_sha1_finish(iot_sha1_context *ctx, unsigned char output[20]);
/* Internal use */
void aliot_sha1_process(iot_sha1_context *ctx, const unsigned char data[64]);
/**
* \brief Output = SHA-1( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-1 checksum result
*/
void aliot_sha1(const unsigned char *input, size_t ilen, unsigned char output[20]);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/byhttp/aliot_sha1.h | C | apache-2.0 | 1,891 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_OSS
#include "oss_app.h"
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#include "utility.h"
#define LOG_TAG "MOD_OSS"
STATIC mp_obj_t obj_uploadFile(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
char *url = NULL;
if (n_args < 5) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
char *key = (char *)mp_obj_str_get_str(args[0]);
char *secret = (char *)mp_obj_str_get_str(args[1]);
char *endPoint = (char *)mp_obj_str_get_str(args[2]);
char *bucketName = (char *)mp_obj_str_get_str(args[3]);
char *filePath = (char *)mp_obj_str_get_str(args[4]);
char *ossPath = NULL;
if (n_args == 6) {
ossPath = (char *)mp_obj_str_get_str(args[5]);
} else {
ossPath = &filePath[1];
}
LOGD(LOG_TAG, "key = %s;\n", key);
LOGD(LOG_TAG, "secret = %s;\n", secret);
LOGD(LOG_TAG, "endPoint = %s;\n", endPoint);
LOGD(LOG_TAG, "bucketName = %s;\n", bucketName);
LOGD(LOG_TAG, "filePath = %s;\n", filePath);
LOGD(LOG_TAG, "ossPath = %s;\n", ossPath);
MP_THREAD_GIL_EXIT();
url = oss_upload_file(key, secret, endPoint, bucketName, filePath, ossPath);
MP_THREAD_GIL_ENTER();
if (url)
return mp_obj_new_strn(url);
else
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(oss_obj_uploadFile, 5, 6, obj_uploadFile);
STATIC mp_obj_t obj_uploadContent(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
char *url = NULL;
if (n_args < 6) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__, n_args);
return mp_const_none;
}
char *key = (char *)mp_obj_str_get_str(args[0]);
char *secret = (char *)mp_obj_str_get_str(args[1]);
char *endPoint = (char *)mp_obj_str_get_str(args[2]);
char *bucketName = (char *)mp_obj_str_get_str(args[3]);
char *fileContent = NULL;
int32_t contentLen = 0;
if ((mp_obj_get_type(args[4]) == &mp_type_bytes) || mp_obj_get_type(args[4]) == &mp_type_bytearray) {
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[4], &bufinfo, MP_BUFFER_READ);
fileContent = bufinfo.buf;
contentLen = bufinfo.len;
} else if (mp_obj_get_type(args[4]) == &mp_type_str) {
fileContent = (char *)mp_obj_str_get_str(args[4]);
contentLen = strlen(fileContent);
}
char *ossFilePath = (char *)mp_obj_str_get_str(args[5]);
LOGD(LOG_TAG, "key = %s;\n", key);
LOGD(LOG_TAG, "secret = %s;\n", secret);
LOGD(LOG_TAG, "endPoint = %s;\n", endPoint);
LOGD(LOG_TAG, "bucketName = %s;\n", bucketName);
LOGD(LOG_TAG, "fileContent = %s;\n", fileContent);
LOGD(LOG_TAG, "ossFilePath = %s;\n", ossFilePath);
MP_THREAD_GIL_EXIT();
url = oss_upload_local_content(key, secret, endPoint, bucketName, fileContent, contentLen, ossFilePath);
MP_THREAD_GIL_ENTER();
if (url)
return mp_obj_new_strn(url);
else
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(oss_obj_uploadContent, 6, obj_uploadContent);
STATIC const mp_rom_map_elem_t oss_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_oss) },
{ MP_ROM_QSTR(MP_QSTR_uploadFile), MP_ROM_PTR(&oss_obj_uploadFile) },
{ MP_ROM_QSTR(MP_QSTR_uploadContent), MP_ROM_PTR(&oss_obj_uploadContent) },
};
STATIC MP_DEFINE_CONST_DICT(oss_locals_dict, oss_locals_dict_table);
const mp_obj_module_t oss_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&oss_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_oss, oss_module, MICROPY_PY_OSS);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/modoss.c | C | apache-2.0 | 3,873 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_OSS_HTTP
#include "aliot_httpapi_oss.h"
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#define LOG_TAG "OSS_HTTP"
STATIC mp_obj_t oss_http_uploadFile(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
char buf[2048] = { 0 };
char *key = (char *)mp_obj_str_get_str(args[0]);
char *secret = (char *)mp_obj_str_get_str(args[1]);
char *endPoint = (char *)mp_obj_str_get_str(args[2]);
char *bucketName = (char *)mp_obj_str_get_str(args[3]);
char *objname = (char *)mp_obj_str_get_str(args[4]);
char *filePath = (char *)mp_obj_str_get_str(args[5]);
ret = oss_http_put_object(key, secret, endPoint, bucketName, objname, filePath, buf, sizeof(buf));
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(oss_http_uploadFile_obj, 6, 6, oss_http_uploadFile);
STATIC mp_obj_t oss_http_uploadContent(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
char buf[2048] = { 0 };
char *key = (char *)mp_obj_str_get_str(args[0]);
char *secret = (char *)mp_obj_str_get_str(args[1]);
char *endPoint = (char *)mp_obj_str_get_str(args[2]);
char *bucketName = (char *)mp_obj_str_get_str(args[3]);
char *objname = (char *)mp_obj_str_get_str(args[4]);
char *contentData = (char *)mp_obj_str_get_str(args[5]);
ret = oss_http_put_content(key, secret, endPoint, bucketName, objname, contentData, buf, sizeof(buf));
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(oss_http_uploadContent_obj, 6, 8, oss_http_uploadContent);
STATIC mp_obj_t oss_http_downloadFile(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
char *range = NULL;
char buf[2048] = { 0 };
char *key = (char *)mp_obj_str_get_str(args[0]);
char *secret = (char *)mp_obj_str_get_str(args[1]);
char *endPoint = (char *)mp_obj_str_get_str(args[2]);
char *bucketName = (char *)mp_obj_str_get_str(args[3]);
char *objname = (char *)mp_obj_str_get_str(args[4]);
char *filePath = (char *)mp_obj_str_get_str(args[5]);
if (n_args == 6) {
range = NULL;
} else if (n_args == 7) {
range = (char *)mp_obj_str_get_str(args[6]);
}
ret = oss_http_get_object(key, secret, endPoint, bucketName, objname, filePath, range, buf, sizeof(buf));
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(oss_http_downloadFile_obj, 6, 7, oss_http_downloadFile);
STATIC const mp_rom_map_elem_t oss_http_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_OSS) },
{ MP_ROM_QSTR(MP_QSTR_uploadFile), MP_ROM_PTR(&oss_http_uploadFile_obj) },
{ MP_ROM_QSTR(MP_QSTR_uploadContent), MP_ROM_PTR(&oss_http_uploadContent_obj) },
{ MP_ROM_QSTR(MP_QSTR_downloadFile), MP_ROM_PTR(&oss_http_downloadFile_obj) },
};
STATIC MP_DEFINE_CONST_DICT(oss_http_locals_dict, oss_http_locals_dict_table);
const mp_obj_module_t oss_http_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&oss_http_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_oss, oss_http_module, MICROPY_PY_OSS_HTTP);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/oss/modosshttp.c | C | apache-2.0 | 3,221 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#include <stdarg.h>
#include <string.h>
#if MICROPY_PY_OTA
#include "board_config.h"
#include "py/builtin.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "py_defines.h"
//#include "be_inl.h"
#include "app_upgrade.h"
#include "module_aiot.h"
#include "ota_agent.h"
#include "ota_import.h"
#include "utility.h"
#include "amp_task.h"
#include "aos/kv.h"
#define MOD_STR "APP_OTA"
static ota_service_t customer_ota_ctx = { 0 };
static ota_store_module_info_t customer_module_info[3];
static aos_task_t user_module_ota_task = { 0 };
static char default_ver[128] = {0};
typedef struct ota_package_info {
int res;
int js_cb_ref;
unsigned int length;
char version[64];
char module_name[64];
int hash_type;
char hash[64];
char store_path[64];
char install_path[64];
char url[256];
} ota_package_info_t;
typedef enum {
ON_TRIGGER = 1,
ON_DOWNLOAD = 2,
ON_VERIFY = 3,
ON_UPGRADE = 4,
} ota_cb_func_t;
static mp_obj_t ota_on_trigger = MP_OBJ_NULL;
static mp_obj_t ota_on_download = MP_OBJ_NULL;
static mp_obj_t ota_on_verify = MP_OBJ_NULL;
static mp_obj_t ota_on_upgrade = MP_OBJ_NULL;
static void ota_install_notify(void *pdata)
{
ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata;
callback_to_python_LoBo(ota_on_upgrade, MP_OBJ_NEW_SMALL_INT(ota_package_info->res), NULL);
aos_free(ota_package_info);
}
static void ota_install_handler(void *pdata)
{
int res = -1;
int js_cb_ref;
ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata;
/* clear jsengine timer, distory js app*/
// amp_module_free();
// app_js_stop();
res = ota_install_pyapp(&customer_ota_ctx, ota_package_info->store_path,
ota_package_info->length,
ota_package_info->install_path);
if (res < 0) {
amp_error(MOD_STR, "module install failed!");
} else {
/*启动app.js*/
// res = ota_load_jsapp(&customer_ota_ctx);
// if(res < 0) {
// amp_error(MOD_STR, "module load failed!");
// }
}
ota_package_info->res = 0;
py_task_schedule_call(ota_install_notify, ota_package_info);
aos_task_exit(0);
}
static mp_obj_t ota_upgrade(mp_obj_t data)
{
int res = -1;
unsigned int length = 0;
const char *install_path = NULL;
const char *store_path = NULL;
aos_task_t ota_install_task;
ota_package_info_t *ota_package_info = NULL;
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "ota_report function param must be dict");
return mp_obj_new_int(-1);
}
/* get verify info */
mp_obj_t index = mp_obj_new_str_via_qstr("length", 6);
length = mp_obj_get_int(mp_obj_dict_get(data, index));
/* get hash_type */
index = mp_obj_new_str_via_qstr("store_path", 10);
store_path = mp_obj_str_get_str(mp_obj_dict_get(data, index));
/* get install_path */
index = mp_obj_new_str_via_qstr("install_path", 12);
install_path = mp_obj_str_get_str(mp_obj_dict_get(data, index));
ota_package_info = aos_malloc(sizeof(ota_package_info_t));
if (!ota_package_info) {
amp_error(MOD_STR, "alloc device notify param fail");
return mp_obj_new_int(-1);
}
memset(ota_package_info, 0x00, sizeof(ota_package_info_t));
ota_package_info->length = length;
strncpy(ota_package_info->store_path, store_path,
sizeof(ota_package_info->store_path));
strncpy(ota_package_info->install_path, install_path,
sizeof(ota_package_info->install_path));
res = aos_task_new_ext(&ota_install_task, "amp ota install task",
ota_install_handler, ota_package_info, 1024 * 4,
AOS_DEFAULT_APP_PRI);
if (res != 0) {
amp_warn(MOD_STR, "iot create task failed");
aos_free(ota_package_info);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_ota_upgrade, ota_upgrade);
static void ota_verify_notify(void *pdata)
{
ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata;
callback_to_python_LoBo(ota_on_verify, MP_OBJ_NEW_SMALL_INT(ota_package_info->res), NULL);
aos_free(ota_package_info);
}
static void ota_verify_handler(void *pdata)
{
int res = -1;
int js_cb_ref;
ota_boot_param_t ota_param = { 0 };
ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata;
memset(&ota_param, 0, sizeof(ota_boot_param_t));
ota_param.len = ota_package_info->length;
ota_param.hash_type = ota_package_info->hash_type;
strncpy(ota_param.hash, ota_package_info->hash,
strlen(ota_package_info->hash));
res = ota_verify_fsfile(&ota_param, ota_package_info->store_path);
if (res < 0) {
amp_error(MOD_STR, "ota verified failed!");
}
ota_package_info->res = res;
py_task_schedule_call(ota_verify_notify, ota_package_info);
aos_task_exit(0);
}
static mp_obj_t py_ota_verify(mp_obj_t data)
{
int res = -1;
// int js_cb_ref;
aos_task_t ota_verify_task;
ota_package_info_t *ota_package_info = NULL;
unsigned int length = 0;
const char *hash_type = NULL;
const char *hash = NULL;
const char *store_path = NULL;
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "ota_report function param must be dict");
return mp_obj_new_int(-1);
}
/* get verify info */
// duk_get_prop_string(ctx, 0, "length");
mp_obj_t index = mp_obj_new_str_via_qstr("length", 6);
length = mp_obj_get_int(mp_obj_dict_get(data, index));
/* get hash_type */
index = mp_obj_new_str_via_qstr("hash_type", 9);
hash_type = mp_obj_str_get_str(mp_obj_dict_get(data, index));
/* get hash */
index = mp_obj_new_str_via_qstr("hash", 4);
hash = mp_obj_str_get_str(mp_obj_dict_get(data, index));
/* get store_path */
index = mp_obj_new_str_via_qstr("store_path", 10);
store_path = mp_obj_str_get_str(mp_obj_dict_get(data, index));
ota_package_info = aos_malloc(sizeof(ota_package_info_t));
if (!ota_package_info) {
amp_error(MOD_STR, "alloc device notify param fail");
return mp_obj_new_int(-1);
}
memset(ota_package_info, 0x00, sizeof(ota_package_info_t));
ota_package_info->length = length;
if (strcmp(hash_type, "null") == 0) {
ota_package_info->hash_type = 0;
} else if (strcmp(hash_type, "md5") == 0) {
ota_package_info->hash_type = 2;
} else if (strcmp(hash_type, "sha256") == 0) {
ota_package_info->hash_type = 1;
} else {
ota_package_info->hash_type = 3;
}
strncpy(ota_package_info->hash, hash, sizeof(ota_package_info->hash));
strncpy(ota_package_info->store_path, store_path,
sizeof(ota_package_info->store_path));
res = aos_task_new_ext(&ota_verify_task, "amp ota verify task",
ota_verify_handler, ota_package_info, 1024 * 5,
AOS_DEFAULT_APP_PRI);
if (res != 0) {
amp_warn(MOD_STR, "iot create task failed");
aos_free(ota_package_info);
}
return mp_obj_new_int(res);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_ota_verify, py_ota_verify);
static void ota_download_notify(void *pdata)
{
ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata;
callback_to_python_LoBo(ota_on_download, MP_OBJ_NEW_SMALL_INT(ota_package_info->res), NULL);
aos_free(ota_package_info);
}
static void ota_download_handler(void *pdata)
{
int res = -1;
int js_cb_ref;
ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata;
res = ota_download_store_fs_start(
ota_package_info->url, strlen(ota_package_info->url),
ota_package_info->store_path,
NULL/*customer_ota_ctx.report_func.report_status_cb*/,
customer_ota_ctx.report_func.param);
if (res < 0) {
amp_error(MOD_STR, "amp jsota download file failed!");
}
ota_package_info->res = res;
py_task_schedule_call(ota_download_notify, ota_package_info);
aos_task_exit(0);
}
static mp_obj_t ota_download(mp_obj_t data)
{
int res = -1;
int js_cb_ref;
aos_task_t ota_download_task;
ota_package_info_t *ota_package_info = NULL;
const char *url = NULL;
const char *store_path = NULL;
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "ota_report function param must be dict");
return mp_obj_new_int(-1);
}
/* get store path */
mp_obj_t index = mp_obj_new_str_via_qstr("url", 3);
url = mp_obj_str_get_str(mp_obj_dict_get(data, index));
/* get url */
index = mp_obj_new_str_via_qstr("store_path", 10);
store_path = mp_obj_str_get_str(mp_obj_dict_get(data, index));
ota_package_info = aos_malloc(sizeof(ota_package_info_t));
if (!ota_package_info) {
amp_error(MOD_STR, "alloc device notify param fail");
return mp_obj_new_int(-1);
}
memset(ota_package_info, 0x00, sizeof(ota_package_info_t));
strncpy(ota_package_info->url, url, sizeof(ota_package_info->url));
strncpy(ota_package_info->store_path, store_path,
sizeof(ota_package_info->store_path));
res = aos_task_new_ext(&ota_download_task, "amp ota download task",
ota_download_handler, ota_package_info, 1024 * 5,
AOS_DEFAULT_APP_PRI);
if (res != 0) {
amp_warn(MOD_STR, "iot create task failed");
aos_free(ota_package_info);
}
return mp_obj_new_int(res);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_ota_download, ota_download);
static mp_obj_t ota_report(mp_obj_t data)
{
int res = -1;
int js_cb_ref;
iot_device_handle_t *iot_device_handle = NULL;
if (!mp_obj_is_dict_or_ordereddict(data)) {
amp_error(MOD_STR, "ota_report function param must be dict");
return mp_obj_new_int(-1);
}
/* get device handle */
mp_obj_t index = mp_obj_new_str_via_qstr("device_handle", 13);
iot_device_handle = (iot_device_handle_t *)MP_OBJ_SMALL_INT_VALUE(mp_obj_dict_get(data, index));
/* get product_key */
index = mp_obj_new_str_via_qstr("product_key", 11);
const char *productkey = mp_obj_str_get_str(mp_obj_dict_get(data, index));
/* get devicename */
index = mp_obj_new_str_via_qstr("device_name", 11);
const char *devicename = mp_obj_str_get_str(mp_obj_dict_get(data, index));
/* get module_name */
index = mp_obj_new_str_via_qstr("module_name", 11);
const char *modulename = mp_obj_str_get_str(mp_obj_dict_get(data, index));
/* get version */
index = mp_obj_new_str_via_qstr("version", 7);
const char *ver = mp_obj_str_get_str(mp_obj_dict_get(data, index));
amp_warn(MOD_STR, "js report ver!");
if (!strncmp(modulename, "default", strlen("default") + 1)) {
strcpy(default_ver, ver);
}
res = ota_transport_inform(iot_device_handle->mqtt_handle, productkey,
devicename, modulename, ver);
if (res < 0) {
amp_error(MOD_STR, "amp pyota report ver failed!");
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_ota_report, ota_report);
static void ota_trigger_notify(void *pdata)
{
ota_package_info_t *ota_package_info = (ota_package_info_t *)pdata;
const char *hash_type = NULL;
if (ota_package_info->hash_type == 0) {
hash_type = "null";
} else if (ota_package_info->hash_type == 1) {
hash_type = "sha256";
} else if (ota_package_info->hash_type == 2) {
hash_type = "md5";
} else {
hash_type = "sha512";
}
mp_sched_carg_t *carg = make_cargs(MP_SCHED_CTYPE_DICT);
make_carg_entry(carg, 0, MP_SCHED_ENTRY_TYPE_INT, ota_package_info->length, NULL, "length");
make_carg_entry(carg, 1, MP_SCHED_ENTRY_TYPE_STR, strlen(ota_package_info->module_name), ota_package_info->module_name, "module_name");
make_carg_entry(carg, 2, MP_SCHED_ENTRY_TYPE_STR, strlen(ota_package_info->version), ota_package_info->version, "version");
make_carg_entry(carg, 3, MP_SCHED_ENTRY_TYPE_STR, strlen(ota_package_info->url), ota_package_info->url, "url");
make_carg_entry(carg, 4, MP_SCHED_ENTRY_TYPE_STR, strlen(ota_package_info->hash), ota_package_info->hash, "hash");
make_carg_entry(carg, 5, MP_SCHED_ENTRY_TYPE_STR, strlen(hash_type), hash_type, "hash_type");
callback_to_python_LoBo(ota_on_trigger, mp_const_none, carg);
aos_free(ota_package_info);
}
/* system image upgrade */
static int32_t customer_upgrade_cb(void *pctx, char *ver, char *module_name,
void *args)
{
int32_t ret = OTA_TRANSPORT_PAR_FAIL;
ota_package_info_t *ota_package_info = NULL;
ota_boot_param_t ota_param = { 0 };
aos_task_t customer_ota_task;
if ((pctx == NULL) || (ver == NULL) || (module_name == NULL) ||
(args == NULL)) {
amp_error(MOD_STR, "amp:ota triggered param err!");
return ret;
}
if (strncmp(module_name, "default", strlen(module_name)) == 0) {
ret = 0;
printf("ver:%s current_ver:%s\r\n", ver, default_ver);
if (strncmp(ver, default_ver, strlen(ver)) <= 0) {
ret = OTA_TRANSPORT_VER_FAIL;
amp_error(MOD_STR, "amp ota version too old!");
} else {
amp_debug(MOD_STR,
"ota version:%s is coming, if OTA upgrade or not ?\n",
ver);
/* clear jsengine timer, distory js app*/
if (aos_task_new_ext(&customer_ota_task, "amp_customer_ota",
internal_sys_upgrade_start, (void *)pctx,
1024 * 4, AOS_DEFAULT_APP_PRI) != 0) {
amp_debug(MOD_STR, "internal ota task create failed!");
ret = OTA_TRANSPORT_PAR_FAIL;
}
amp_debug(MOD_STR, "app management center start");
}
} else {
/*读取ota 触发时云端下发的文件信息*/
ret = ota_read_parameter(&ota_param);
if (ret < 0) {
amp_error(MOD_STR, "get store ota param info failed\n");
}
ota_package_info = aos_malloc(sizeof(ota_package_info_t));
if (!ota_package_info) {
amp_error(MOD_STR, "alloc device notify param fail");
return -1;
}
ota_package_info->js_cb_ref = (int)args;
ota_package_info->length = ota_param.len;
ota_package_info->hash_type = ota_param.hash_type;
strncpy(ota_package_info->url, ota_param.url,
sizeof(ota_package_info->url));
strncpy(ota_package_info->version, ver, strlen(ver));
strncpy(ota_package_info->module_name, module_name,
strlen(module_name));
strncpy(ota_package_info->hash, ota_param.hash,
sizeof(ota_package_info->hash));
/** todo call ota_trigger_notify */
py_task_schedule_call(ota_trigger_notify, ota_package_info);
}
return OTA_SUCCESS;
}
static mp_obj_t ota_init(mp_obj_t data)
{
int res = -1;
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;
iot_device_handle_t *iot_device_handle = NULL;
ota_package_info_t *ota_package_info = NULL;
if (!mp_obj_is_dict_or_ordereddict(data)) {
return mp_obj_new_int(res);
}
/* get http request url */
mp_obj_t index = mp_obj_new_str_via_qstr("device_handle", 13);
iot_device_handle = (iot_device_handle_t *)MP_OBJ_SMALL_INT_VALUE(mp_obj_dict_get(data, index));
ota_service_param_reset(&customer_ota_ctx);
/* get device info
todo:save kv when do device_connect
*/
aos_kv_get(AMP_CUSTOMER_PRODUCTKEY, customer_ota_ctx.pk, &productkey_len);
aos_kv_get(AMP_CUSTOMER_PRODUCTSECRET, customer_ota_ctx.ps,
&productsecret_len);
aos_kv_get(AMP_CUSTOMER_DEVICENAME, customer_ota_ctx.dn, &devicename_len);
aos_kv_get(AMP_CUSTOMER_DEVICESECRET, customer_ota_ctx.ds,
&devicesecret_len);
memset(customer_module_info, 0x00, sizeof(customer_module_info));
customer_ota_ctx.mqtt_client = (void *)iot_device_handle->mqtt_handle;
ota_package_info = aos_malloc(sizeof(ota_package_info_t));
if (!ota_package_info) {
amp_error(MOD_STR, "alloc device notify param fail");
goto out;
}
memset(ota_package_info, 0, sizeof(ota_package_info_t));
ota_package_info->js_cb_ref = 0;
ota_register_module_store(&customer_ota_ctx, customer_module_info, 3);
ota_register_trigger_msg_cb(&customer_ota_ctx, (void *)customer_upgrade_cb,
(void *)1);
/* init ota service */
res = ota_service_init(&customer_ota_ctx);
if (res < 0) {
amp_error(MOD_STR, "customer ota init failed!");
} else {
amp_error(MOD_STR, "customer ota init success!");
}
out:
if (res < 0) {
// todo:ota_package_info->js_cb_ref 是否需要free?
if (ota_package_info != NULL) {
aos_free(ota_package_info);
}
return mp_obj_new_int(-1);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_ota_init, ota_init);
STATIC mp_obj_t ota_register_cb(mp_obj_t id, mp_obj_t func)
{
int res = -1;
int callback_id = mp_obj_get_int(id);
switch (callback_id) {
case ON_TRIGGER:
ota_on_trigger = func;
break;
case ON_DOWNLOAD:
ota_on_download = func;
break;
case ON_VERIFY:
ota_on_verify = func;
break;
case ON_UPGRADE:
ota_on_upgrade = func;
break;
default:
break;
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_ota_register_cb, ota_register_cb);
STATIC const mp_rom_map_elem_t ota_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ota) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_init), MP_ROM_PTR(&native_ota_init) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_on), MP_ROM_PTR(&native_ota_register_cb) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_download), MP_ROM_PTR(&native_ota_download) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_verify), MP_ROM_PTR(&native_ota_verify) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_report), MP_ROM_PTR(&native_ota_report) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_upgrade), MP_ROM_PTR(&native_ota_upgrade) },
};
STATIC MP_DEFINE_CONST_DICT(ota_module_globals, ota_module_globals_table);
const mp_obj_module_t mp_module_ota = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&ota_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_ota, mp_module_ota, MICROPY_PY_OTA);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/ota/modota.c | C | apache-2.0 | 18,891 |
# CMake fragment for MicroPython port extmod component
set(MICROPY_MODULES_PORT_DIR ${CMAKE_CURRENT_LIST_DIR})
include("${CMAKE_CURRENT_LIST_DIR}/config.cmake")
set(MICROPY_INC_MODULES_PORT
${AOS_COMPONENTS_DIR}/osal_aos/include
${AOS_COMPONENTS_DIR}/ulog/include
)
if(MICROPY_PY_AIAGENT)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_AIAGENT=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aiagent/modaiagent.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aiagent/aiagent.c)
endif()
if(M5STACK_CORE2)
set(BOARD_M5STACKCORE2 TRUE)
endif()
if(IDF_TARGET STREQUAL "esp32")
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/soc/soc/esp32/include)
elseif(IDF_TARGET STREQUAL "esp32c3")
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/soc/esp32c3/include)
elseif(IDF_TARGET STREQUAL "esp32s2")
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/soc/esp32s2/include)
elseif(IDF_TARGET STREQUAL "esp32s3")
list(APPEND MICROPY_INC_MODULES_PORT $ENV{IDF_PATH}/components/soc/esp32s3/include)
endif()
if(MICROPY_PY_ALIYUNIOT)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_ALIYUNIOT=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/modaliyunIoT.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/module_aiot_activeinfo.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/module_aiot_device.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/module_aiot_dynreg.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/module_aiot_gateway.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/module_aiot_mqtt.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/module_aiot_ntp.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT/module_aiot_upload.c)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aliyunIoT)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/linksdk/components/data-model)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/linksdk/components/dynreg)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/linksdk/components/subdev)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/linksdk/components/devinfo)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/linksdk/components/ntp)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/linksdk/components/mqtt-upload)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/linksdk/core)
endif()
if(MICROPY_PY_BLE)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_BLE=1)
list(APPEND MICROPY_DEF_MODULES_PORT CONFIG_BT=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/ble/modble.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/ble/bt_gatts_adapter.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/ble/bt_host_adapter.c)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/ble)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ble_host/bt_host/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ble_host/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ble_host/include)
endif()
if(MICROPY_PY_CHANNEL_ENABLE)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_CHANNEL_ENABLE=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/online_upgrade/modonline_upgrade.c)
endif()
if(MICROPY_PY_HTTP)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_HTTP=1)
if(ESP_PLATFORM)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/network/http/esp32/modhttp.c)
endif()
if(HAAS_PLATFORM)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/network/http/aos/modhttp.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/network/http/aos/httpclient.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/http/include)
endif()
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/network/http)
endif()
if(MICROPY_PY_MODBUS)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_MODBUS=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/modbus/modbus.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/mbmaster/include)
endif()
if(MICROPY_PY_KV)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_KV=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/kv/modkv.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/kv/include)
endif()
if(MICROPY_PY_OTA)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_OTA=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/ota/modota.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ota/include)
endif()
if(MICROPY_PY_OSS)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_OSS=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/oss/modoss.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/oss/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/oss/src)
elseif(MICROPY_PY_OSS_HTTP)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_OSS_HTTP=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/oss/modosshttp.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/oss/byhttp/aliot_base64.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/oss/byhttp/aliot_hmac.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/oss/byhttp/aliot_httpapi_oss.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/oss/byhttp/aliot_sha1.c)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/oss/byhttp)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/http/include)
endif()
if(MICROPY_PY_UCLOUD_AI)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_UCLOUD_AI=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aiagent/aiagent.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/aiagent/modaiagent.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ai_agent/include)
endif()
if(MICROPY_PY_MINICV)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_MINICV=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/modminicv.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/datainput.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/imagecodec.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/imageproc.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/ml.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/ui.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/videocodec.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/c/src/WrapperIHaasDataInput.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/c/src/WrapperIHaasImageCodec.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/c/src/WrapperIHaasImageProc.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/c/src/WrapperIHaasML.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/c/src/WrapperIHaasUI.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/c/src/WrapperIHaasVideoCodec.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/core/src/HaasImageUtils.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/ml/src/HaasML.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/ml/src/HaasMLCloud.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/ml/src/HaasMLMnn.cpp)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/minicv/base/modules/ml/src/HaasMLOlda.cpp)
list(APPEND MICROPY_INC_MODULES_PORT ${HAAS_ENGINE_DIR}/modules/minicv)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ucloud_ai/include)
endif()
if(MICROPY_PY_UCAMERA)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_UCAMERA=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/ucamera/moducamera.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ucamera/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ucamera/include/device/wifi)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ucamera/include/device/uart)
endif()
if(MICROPY_PY_DRIVER)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_DRIVER=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/moddriver.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/board_mgr.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/pwm.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/adc.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/timer.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/i2c.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/spi.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/uart.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/gpio.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/driver/wdt.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/amp_adapter/include/peripheral)
if(HAAS_PLATFORM)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/drivers/peripheral/gpio/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/drivers/core/base/include)
endif()
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/cjson/include)
endif()
if(MICROPY_PY_AUDIO)
include("${MICROPY_MODULES_PORT_DIR}/audio/CMakeLists.txt")
endif()
if(MICROPY_PY_SNTP)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_SNTP=1)
if(HAAS_PLATFORM)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/sntp/aos/modsntp.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/sntp/include)
elseif(ESP_PLATFORM)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/sntp/esp32/modsntp.c)
endif()
endif()
if(MICROPY_PY_LVGL)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_LVGL=1)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_DIR}/lib/lv_bindings)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_DIR}/lib/lv_bindings/lvgl)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_DIR}/lib/lv_bindings/lvgl/src)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/freetype/include)
if(HAAS_PLATFORM)
#list(APPEND MICROPY_DEF_MODULES_PORT LV_CONF_INCLUDE_SIMPLE=1)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display/haas)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/drivers/external_device/ft6336/include)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display/haas/moddisplay.c)
endif()
if(ESP_PLATFORM)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/drivers/external_device/m5driver/i2c_manager)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/drivers/external_device/m5driver/i2c_manager/i2c_manager)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/drivers/external_device/m5driver/axp192)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/drivers/external_device/m5driver/lvgl_esp32_drivers)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display/esp32)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display/esp32/moddisplay.c)
endif()
endif()
if(MICROPY_PY_TFT)
if(ESP_PLATFORM)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_TFT=1)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display/esp32)
list(APPEND MICROPY_INC_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display/esp32/tft)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/display/esp32/modtft.c)
file(GLOB_RECURSE TFT_SOURCES ${MICROPY_MODULES_PORT_DIR}/display/esp32/tft/*.c)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${TFT_SOURCES})
endif()
endif()
if(MICROPY_PY_BLECFG)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_BLECFG=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/netconfig/blecfg.c)
endif()
if(MICROPY_PY_NETMGR)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_NETMGR=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/netmgr/modnetmgr.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/uservice/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/netmgr/include)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/amp_adapter/include)
endif()
if(MICROPY_PY_ULOG)
list(APPEND MICROPY_DEF_MODULES_PORT MICROPY_PY_ULOG=1)
list(APPEND MICROPY_SOURCE_MODULES_PORT ${MICROPY_MODULES_PORT_DIR}/ulog/modulog.c)
list(APPEND MICROPY_INC_MODULES_PORT ${AOS_COMPONENTS_DIR}/ulog/include)
endif()
| YifuLiu/AliOS-Things | components/py_engine/modules/portmod.cmake | CMake | apache-2.0 | 14,074 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#if MICROPY_PY_SNTP
#include "lwip/apps/sntp.h"
#include "py/obj.h"
#include "ulog/ulog.h"
#define TAG "MOD_SNTP"
static const char *m_sntp_servaddr[] = {
"cn.pool.ntp.org",
"ntp.aliyun.com",
"ntp.tuna.tsinghua.edu.cn",
};
STATIC mp_obj_t mp_sntp_settime(size_t n_args, const mp_obj_t *args)
{
char *serv_addr = "ntp.aliyun.com";
char *timezone = "CST-8";
if (n_args == 1) {
timezone = mp_obj_str_get_str(args[0]);
} else if (n_args == 2) {
timezone = mp_obj_str_get_str(args[0]);
serv_addr = mp_obj_str_get_str(args[1]);
}
struct timezone tz = {0};
tz.tz_minuteswest = -480;
tz.tz_dsttime = 0;
sntp_set_timezone(&tz);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_sntp_settime_obj, 0, 2, mp_sntp_settime);
STATIC const mp_rom_map_elem_t sntp_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_sntp) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_setTime), MP_ROM_PTR(&mp_sntp_settime_obj) },
};
STATIC MP_DEFINE_CONST_DICT(sntp_module_globals, sntp_module_globals_table);
const mp_obj_module_t sntp_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&sntp_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_sntp, sntp_module, MICROPY_PY_SNTP);
#endif // MICROPY_PY_SNTP
| YifuLiu/AliOS-Things | components/py_engine/modules/sntp/aos/modsntp.c | C | apache-2.0 | 1,408 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_SNTP
#include "esp_log.h"
#include "esp_sntp.h"
#include "py/obj.h"
#include "sntp/sntp.h"
#define TAG "MOD_SNTP"
static bool obtain_time(const char *serv_addr)
{
if (sntp_enabled()) {
sntp_stop();
}
sntp_setoperatingmode(SNTP_OPMODE_POLL);
sntp_setservername(0, serv_addr);
sntp_init();
// wait for time to be set
time_t now = 0;
struct tm timeinfo = { 0 };
int retry_count = 20;
int retry = 0;
while (sntp_get_sync_status() == SNTP_SYNC_STATUS_RESET && ++retry < retry_count) {
ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
if (retry == retry_count) {
ESP_LOGE(TAG, "Failed to get sntp time within %d seconds", retry_count);
return false;
}
time(&now);
localtime_r(&now, &timeinfo);
return true;
}
STATIC mp_obj_t mp_sntp_settime(size_t n_args, const mp_obj_t *args)
{
char *timezone = "CST-8";
char *serv_addr = "cn.pool.ntp.org";
if (n_args == 1) {
timezone = mp_obj_str_get_str(args[0]);
} else if (n_args == 2) {
timezone = mp_obj_str_get_str(args[0]);
serv_addr = mp_obj_str_get_str(args[1]);
}
time_t now;
struct tm timeinfo;
time(&now);
localtime_r(&now, &timeinfo);
// Is time set? If not, tm_year will be (1970 - 1900).
if (timeinfo.tm_year < (2016 - 1900)) {
ESP_LOGI(TAG, "Time is not set yet. Connecting to WiFi and getting time over NTP.");
if (obtain_time(serv_addr) == false) {
sntp_stop();
return MP_OBJ_NEW_SMALL_INT(-1);
}
// update 'now' variable with current time
time(&now);
}
char strftime_buf[64] = { 0 };
setenv("TZ", timezone, 1);
tzset();
localtime_r(&now, &timeinfo);
strftime(strftime_buf, sizeof(strftime_buf), "%c", &timeinfo);
ESP_LOGI(TAG, "The current date/time in China is: %s", strftime_buf);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_sntp_settime_obj, 0, 2, mp_sntp_settime);
STATIC const mp_rom_map_elem_t sntp_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_sntp) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_setTime), MP_ROM_PTR(&mp_sntp_settime_obj) },
};
STATIC MP_DEFINE_CONST_DICT(sntp_module_globals, sntp_module_globals_table);
const mp_obj_module_t sntp_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&sntp_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_sntp, sntp_module, MICROPY_PY_SNTP);
#endif // MICROPY_PY_SNTP
| YifuLiu/AliOS-Things | components/py_engine/modules/sntp/esp32/modsntp.c | C | apache-2.0 | 2,693 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_SYSTEM
#include "amp_utils.h"
#include "aos/kernel.h"
#include "aos_system.h"
#include "genhdr/mpversion.h"
#include "py/builtin.h"
#include "py/mpconfig.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/obj.h"
#include "py/objstr.h"
#include "py/objtuple.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#define LOG_TAG "MOD_SYSTEM"
STATIC const qstr os_uname_info_fields[] = { MP_QSTR_sysname, MP_QSTR_nodename, MP_QSTR_release, MP_QSTR_version,
MP_QSTR_machine };
STATIC const MP_DEFINE_STR_OBJ(os_uname_info_sysname_obj, MICROPY_PY_SYS_PLATFORM);
STATIC const MP_DEFINE_STR_OBJ(os_uname_info_nodename_obj, MICROPY_PY_SYS_NODE);
STATIC const MP_DEFINE_STR_OBJ(os_uname_info_release_obj, MICROPY_VERSION_STRING);
STATIC const MP_DEFINE_STR_OBJ(os_uname_info_version_obj, MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE);
STATIC const MP_DEFINE_STR_OBJ(os_uname_info_machine_obj, MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME);
STATIC MP_DEFINE_ATTRTUPLE(os_uname_info_obj, os_uname_info_fields, 5, (mp_obj_t)&os_uname_info_sysname_obj,
(mp_obj_t)&os_uname_info_nodename_obj, (mp_obj_t)&os_uname_info_release_obj,
(mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj);
STATIC mp_obj_t obj_getInfo()
{
return (mp_obj_t)&os_uname_info_obj;
}
MP_DEFINE_CONST_FUN_OBJ_0(native_get_system_info, obj_getInfo);
STATIC mp_obj_t obj_sleep(void)
{
// aos_system_sleep();
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(native_sleep_system, obj_sleep);
STATIC mp_obj_t obj_reboot(void)
{
aos_reboot();
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_0(native_reset_system, obj_reboot);
STATIC mp_obj_t obj_getUptime()
{
uint64_t begin_ms = aos_now_ms();
return MP_ROM_INT(begin_ms);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(native_get_system_uptime, obj_getUptime);
STATIC mp_obj_t obj_getMemory()
{
int32_t ret = -1;
amp_heap_info_t heap_info;
ret = amp_heap_memory_info(&heap_info);
if (ret != 0) {
LOGE(LOG_TAG, "get heap memory failed");
return mp_const_none;
}
mp_obj_t dict = mp_obj_new_dict(3);
mp_obj_dict_store(dict, mp_obj_new_str("total", strlen("total")), mp_obj_new_int(heap_info.heap_total));
mp_obj_dict_store(dict, mp_obj_new_str("used", strlen("used")), mp_obj_new_int(heap_info.heap_used));
mp_obj_dict_store(dict, mp_obj_new_str("free", strlen("free")), mp_obj_new_int(heap_info.heap_free));
return dict;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(native_get_memory_info, obj_getMemory);
STATIC const mp_rom_map_elem_t system_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_system) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getInfo), MP_ROM_PTR(&native_get_system_info) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_sleep), MP_ROM_PTR(&native_sleep_system) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_reboot), MP_ROM_PTR(&native_reset_system) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getUptime), MP_ROM_PTR(&native_get_system_uptime) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getMemory), MP_ROM_PTR(&native_get_memory_info) },
};
STATIC MP_DEFINE_CONST_DICT(system_module_globals, system_module_globals_table);
const mp_obj_module_t system_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&system_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_system, system_module, MICROPY_PY_SYSTEM);
#endif // MICROPY_PY_SYSTEM | YifuLiu/AliOS-Things | components/py_engine/modules/system/modsystem.c | C | apache-2.0 | 3,535 |
#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"
#include "ucamera_service.h"
#include "ulog/ulog.h"
#include "wifi_camera.h"
#include "stdatomic.h"
#define LOG_TAG "MOD_UCAMERA"
#if MICROPY_PY_UCAMERA
// this is the actual C-structure for our new object
typedef struct
{
cam_dev_type_t cam_dev_type;
} mp_ml_obj_t;
mp_ml_obj_t *ucamera_obj = NULL;
STATIC mp_obj_t obj_init(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_obj_new_int(ret);
}
ucamera_obj = m_new_obj(mp_ml_obj_t);
char *camera_type = (char *)mp_obj_str_get_str(args[0]);
if (!strcmp(camera_type, "wifi")) {
ucamera_obj->cam_dev_type = CAM_WIFI_TYPE;
ret = ucamera_service_init(WIFI_CAMERA_NAME);
if (ret < 0) {
LOGD(LOG_TAG, "ucamera_service_init failed %s;\n", __func__);
}
} else if (!strcmp(camera_type, "uart")) {
uart_cam_params_t params;
uint32_t rx = (uint32_t)mp_obj_get_int(args[1]);
uint32_t tx = (uint32_t)mp_obj_get_int(args[2]);
ucamera_obj->cam_dev_type = CAM_UART_TYPE;
ret = ucamera_service_init(UART_CAMERA_NAME);
if (ret < 0) {
LOGD(LOG_TAG, "ucamera_service_init failed %s;\n", __func__);
}
// set bandrate
params.bandrate = 1500000;
params.rx = rx;
params.tx = tx;
ret = ucamera_service_config(UCAMERA_CMD_SET_UART_PARAMS, (void *)¶ms);
if (ret < 0) {
LOGD(LOG_TAG, "init failed %s;\n", __func__);
}
} else {
ret = -1;
LOGE(LOG_TAG, "unsupport camera type %s yet\n", __func__);
}
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_init, 1, obj_init);
STATIC mp_obj_t obj_connect(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_obj_new_int(ret);
}
if (ucamera_obj->cam_dev_type != CAM_WIFI_TYPE)
return mp_obj_new_int(ret);
char *camera_url = (char *)mp_obj_str_get_str(args[0]);
if (camera_url != NULL) {
ret = ucamera_service_connect(camera_url);
} else {
ret = -1;
LOGE(LOG_TAG, "camera_url can not be null %s;\n", __func__);
}
if (ret < 0) {
LOGD(LOG_TAG, "ucamera connect failed %s;\n", __func__);
}
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_connect, 1, obj_connect);
STATIC mp_obj_t obj_disconnect(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
if (ucamera_obj->cam_dev_type != CAM_WIFI_TYPE)
return mp_obj_new_int(ret);
ret = ucamera_service_disconnect();
if (ret < 0) {
LOGD(LOG_TAG, "ucamera config failed %s;\n", __func__);
}
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_disconnect, 0, obj_disconnect);
STATIC mp_obj_t obj_config(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_obj_new_int(ret);
}
if (ucamera_obj->cam_dev_type != CAM_WIFI_TYPE)
return mp_obj_new_int(ret);
char *camera_control_url = (char *)mp_obj_str_get_str(args[0]);
if (camera_control_url != NULL) {
ret = ucamera_service_config(UCAMERA_CMD_SET_CONTROL_URL, (void *)camera_control_url);
} else {
ret = -1;
LOGE(LOG_TAG, "camera_control_url can not be null %s;\n", __func__);
}
if (ret < 0) {
LOGD(LOG_TAG, "ucamera config failed %s;\n", __func__);
}
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_config, 1, obj_config);
STATIC mp_obj_t obj_setProp(size_t n_args, const mp_obj_t *args)
{
int32_t ret = -1;
frame_size_t frame_size;
uart_cam_params_t params;
uint32_t time = 0;
if (n_args < 2) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_obj_new_int(ret);
}
uint32_t cmd_id = mp_obj_get_int(args[0]);
switch (cmd_id) {
case UCAMERA_CMD_SET_FRAME_SIZE:
frame_size.id = mp_obj_get_int(args[1]);
ret = ucamera_service_config(UCAMERA_CMD_SET_FRAME_SIZE, (void *)&frame_size);
break;
case UCAMERA_CMD_SET_UPLOAD_TIME:
time = mp_obj_get_int(args[1]);
ret = ucamera_service_config(UCAMERA_CMD_SET_UPLOAD_TIME, (void *)&time);
break;
case UCAMERA_CMD_SET_MODE:
params.mode = mp_obj_get_int(args[1]);
ret = ucamera_service_config(UCAMERA_CMD_SET_MODE, (void *)¶ms);
break;
case UCAMERA_CMD_SET_WIFI_SSID_PWD:
params.wifi_ssid = mp_obj_str_get_str(args[1]);
params.wifi_pwd = mp_obj_str_get_str(args[1]);
ret = ucamera_service_config(UCAMERA_CMD_SET_WIFI_SSID_PWD, (void *)¶ms);
break;
case UCAMERA_CMD_SET_LED_BRIGHTNESS:
params.led_brightness = mp_obj_get_int(args[1]);
ret = ucamera_service_config(UCAMERA_CMD_SET_LED_BRIGHTNESS, (void *)¶ms);
break;
default:
break;
}
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ucamera_obj_setProp, 2, 3, obj_setProp);
STATIC mp_obj_t obj_getProp(size_t n_args, const mp_obj_t *args)
{
int32_t ret = -1;
if (n_args < 1) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_obj_new_int(ret);
}
uint32_t cmd_id = mp_obj_get_int(args[0]);
switch (cmd_id) {
case UCAMERA_CMD_GET_TOKEN:
/* code */
printf("not support yet\n");
break;
default:
break;
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_getProp, 1, obj_getProp);
STATIC mp_obj_t obj_capture(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
frame_buffer_t *frame = NULL;
mp_obj_t *mp_frame = NULL;
/*get one camera frame*/
MP_THREAD_GIL_EXIT();
frame = ucamera_service_get_frame();
MP_THREAD_GIL_ENTER();
if (!frame) {
LOGE(LOG_TAG, "ucamera get frame fail\n");
mp_printf(MP_PYTHON_PRINTER, "ucamera get frame fail\n");
return mp_const_none;
} else {
LOGD(LOG_TAG, "ucamera get frame OK!\n");
}
if (frame) {
if (frame->len > 0) {
mp_frame = mp_obj_new_bytes(frame->buf, frame->len);
if (frame->buf) {
free(frame->buf);
frame->buf = NULL;
}
return mp_frame;
} else {
return mp_const_none;
}
}
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_capture, 0,
obj_capture);
STATIC mp_obj_t obj_save(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
if (n_args < 2) {
LOGE(LOG_TAG, "%s: args num is illegal :n_args = %d;\n", __func__,
n_args);
return mp_obj_new_int(ret);
}
frame_buffer_t frame;
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ);
frame.buf = bufinfo.buf;
frame.len = bufinfo.len;
printf("frame.len: %d\n", frame.len);
char *path = (char *)mp_obj_str_get_str(args[1]);
/*save frame to jpeg file*/
ret = ucamera_service_save_frame(&frame, path);
if (ret < 0) {
LOGE(LOG_TAG, "save image fail\n");
} else {
LOGD(LOG_TAG, "save image to %s successfully!\n", path);
}
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_save, 1,
obj_save);
STATIC mp_obj_t obj_uninit(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
ret = ucamera_service_uninit();
if (ret < 0) {
LOGD(LOG_TAG, "init failed %s;\n", __func__);
}
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(ucamera_obj_uninit, 0, obj_uninit);
STATIC const mp_rom_map_elem_t ucamera_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucamera) },
{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&ucamera_obj_init) },
{ MP_ROM_QSTR(MP_QSTR_connect), MP_ROM_PTR(&ucamera_obj_connect) },
{ MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&ucamera_obj_disconnect) },
{ MP_ROM_QSTR(MP_QSTR_config), MP_ROM_PTR(&ucamera_obj_config) },
{ MP_ROM_QSTR(MP_QSTR_uninit), MP_ROM_PTR(&ucamera_obj_uninit) },
{ MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&ucamera_obj_capture) },
{ MP_ROM_QSTR(MP_QSTR_save), MP_ROM_PTR(&ucamera_obj_save) },
{ MP_ROM_QSTR(MP_QSTR_setProp), MP_ROM_PTR(&ucamera_obj_setProp) },
{ MP_ROM_QSTR(MP_QSTR_getProp), MP_ROM_PTR(&ucamera_obj_getProp) },
{ MP_ROM_QSTR(MP_QSTR_SIZE_800X600), MP_ROM_INT(9)},
{ MP_ROM_QSTR(MP_QSTR_SIZE_640X480), MP_ROM_INT(8)},
{ MP_ROM_QSTR(MP_QSTR_SIZE_320X240), MP_ROM_INT(5)},
{ MP_ROM_QSTR(MP_QSTR_SIZE_240X240), MP_ROM_INT(4)},
{ MP_ROM_QSTR(MP_QSTR_SIZE_160X120), MP_ROM_INT(1)},
{ MP_ROM_QSTR(MP_QSTR_UART_MODE), MP_ROM_INT(CAM_UART_MODE)},
{ MP_ROM_QSTR(MP_QSTR_CLOUD_MODE), MP_ROM_INT(CAM_TIMING_MODE)},
{ MP_ROM_QSTR(MP_QSTR_WIFI_STA_MODE), MP_ROM_INT(CAM_WIFI_STA_MODE)},
{ MP_ROM_QSTR(MP_QSTR_SET_FRAME_SIZE), MP_ROM_INT(UCAMERA_CMD_SET_FRAME_SIZE)},
// { MP_ROM_QSTR(MP_QSTR_SET_UPLOAD_TIME), MP_ROM_INT(UCAMERA_CMD_SET_UPLOAD_TIME)},
{ MP_ROM_QSTR(MP_QSTR_SET_MODE), MP_ROM_INT(UCAMERA_CMD_SET_MODE)},
{ MP_ROM_QSTR(MP_QSTR_SET_WIFI_SSID_PWD), MP_ROM_INT(UCAMERA_CMD_SET_WIFI_SSID_PWD)},
{ MP_ROM_QSTR(MP_QSTR_SET_LED_BRIGHTNESS), MP_ROM_INT(UCAMERA_CMD_SET_LED_BRIGHTNESS)},
};
STATIC MP_DEFINE_CONST_DICT(ucamera_locals_dict, ucamera_locals_dict_table);
const mp_obj_module_t ucamera_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&ucamera_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_ucamera, ucamera_module, MICROPY_PY_UCAMERA);
#endif // MICROPY_PY_SYSTEM
| YifuLiu/AliOS-Things | components/py_engine/modules/ucamera/moducamera.c | C | apache-2.0 | 11,067 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "oss_app.h"
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ucloud_ai_chatbot.h"
#include "ulog/ulog.h"
#define LOG_TAG "MOD_CHATBOT"
extern const mp_obj_type_t chatbot_type;
#define CHATBOT_CHECK_PARAMS() \
chatbot_obj_t *self = (chatbot_obj_t *)MP_OBJ_TO_PTR(self_in); \
do { \
if (self == NULL) { \
mp_raise_OSError(MP_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;
} chatbot_obj_t;
static chatbot_obj_t *chatbot_obj = NULL;
STATIC mp_obj_t chatbot_new(const mp_obj_type_t *type, size_t n_args,
size_t n_kw, const mp_obj_t *args)
{
chatbot_obj = m_new_obj(chatbot_obj_t);
if (!chatbot_obj) {
mp_raise_OSError(MP_ENOMEM);
return mp_const_none;
}
memset(chatbot_obj, 0, sizeof(chatbot_obj));
chatbot_obj->base.type = &chatbot_type;
chatbot_obj->modName = "chatbot";
return MP_OBJ_FROM_PTR(chatbot_obj);
}
void chatbot_print(const mp_print_t *print, mp_obj_t self_in,
mp_print_kind_t kind)
{
chatbot_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->modName);
}
STATIC mp_obj_t obj_input(size_t n_args, const mp_obj_t *args)
{
LOGD(LOG_TAG, "entern %s; n_args = %d;\n", __func__, n_args);
int ret = -1;
char *response = NULL;
char buffer[2048];
if (n_args < 6) {
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];
CHATBOT_CHECK_PARAMS();
char *key = (char *)mp_obj_str_get_str(args[1]);
char *secret = (char *)mp_obj_str_get_str(args[2]);
char *instanceId = (char *)mp_obj_str_get_str(args[3]);
char *sessionId =
mp_obj_is_str(args[4]) ? (char *)mp_obj_str_get_str(args[4]) : NULL;
char *text = (char *)mp_obj_str_get_str(args[5]);
LOGD(LOG_TAG, "key = %s;\n", key);
LOGD(LOG_TAG, "secret = %s;\n", secret);
LOGD(LOG_TAG, "instanceId = %s;\n", instanceId);
LOGD(LOG_TAG, "sessionId = %s\n", sessionId);
LOGD(LOG_TAG, "text = %s;\n", text);
ucloud_ai_set_key_secret(key, secret);
response = ucloud_ai_chatbot(instanceId, sessionId, text);
if (!response)
return mp_const_none;
if (strlen(response) > 2048) {
LOGE(LOG_TAG, "buffer is not enough\n");
free(response);
return mp_const_none;
}
strcpy(buffer, response);
free(response);
return mp_obj_new_strn(buffer);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(chatbot_obj_input, 6, obj_input);
STATIC const mp_rom_map_elem_t chatbot_locals_dict_table[] = {
{ MP_ROM_QSTR(MP_QSTR_input), MP_ROM_PTR(&chatbot_obj_input) },
};
STATIC MP_DEFINE_CONST_DICT(chatbot_locals_dict, chatbot_locals_dict_table);
const mp_obj_type_t chatbot_type = {
.base = { &mp_type_type },
.name = MP_QSTR_ChatBot,
.print = chatbot_print,
.make_new = chatbot_new,
.locals_dict = (mp_obj_dict_t *)&chatbot_locals_dict,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/ucloud_ai/chatbot.c | C | apache-2.0 | 3,586 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_UCLOUD_AI
#include "py/builtin.h"
#include "py/mperrno.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "ulog/ulog.h"
#include "ucloud_ai_common.h"
#include "utility.h"
#define LOG_TAG "MOD_UCLOUD_AI"
extern const mp_obj_type_t chatbot_type;
STATIC mp_obj_t obj_get_token_id(size_t n_args, const mp_obj_t *args)
{
char *obj_key = (char *)mp_obj_str_get_str(args[0]);
char *obj_secret = (char *)mp_obj_str_get_str(args[1]);
char *obj_domain = (char *)mp_obj_str_get_str(args[2]);
char *obj_region_id = (char *)mp_obj_str_get_str(args[3]);
char buffer[512];
char *response = NULL;
LOGD(LOG_TAG, "obj_key = %s;\n", obj_key);
LOGD(LOG_TAG, "obj_secret = %s;\n", obj_secret);
LOGD(LOG_TAG, "obj_domain = %s;\n", obj_domain);
LOGD(LOG_TAG, "obj_region_id = %s;\n", obj_region_id);
ucloud_ai_set_key_secret(obj_key, obj_secret);
response = ucloud_ai_get_token_id(obj_domain, obj_region_id);
if (!response)
return mp_const_none;
if (strlen(response) > 512) {
LOGE(LOG_TAG, "buffer is not enough\n");
free(response);
return mp_const_none;
}
strcpy(buffer, response);
free(response);
return mp_obj_new_strn(buffer);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_obj_get_token_id, 4, obj_get_token_id);
STATIC mp_obj_t obj_compute_md5(mp_obj_t data, size_t size)
{
char *response = NULL;
char md5[100];
if (data == NULL || size <= 0)
return mp_const_none;
char *obj_data = (char *)mp_obj_str_get_str(data);
response = ucloud_ai_compute_md5(data, size);
if (!response)
return mp_const_none;
strcpy(md5, response);
free(response);
return mp_obj_new_strn(md5);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_compute_md5, obj_compute_md5);
STATIC mp_obj_t obj_generate_uuid(void)
{
char *response = NULL;
char uuid[36];
response = ucloud_ai_generate_uuid();
if (!response)
return mp_const_none;
strcpy(uuid, response);
free(response);
return mp_obj_new_strn(uuid);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_obj_generate_uuid, obj_generate_uuid);
STATIC mp_obj_t obj_url_encode(mp_obj_t src)
{
char *response = NULL;
char *obj_src = (char *)mp_obj_str_get_str(src);
response = ucloud_ai_url_encode(obj_src);
if (!response)
return mp_const_none;
mp_obj_t obj_encoded = mp_obj_new_strn(response);
return obj_encoded;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_obj_url_encode, obj_url_encode);
STATIC mp_obj_t obj_url_decode(mp_obj_t src)
{
char *response = NULL;
char *obj_src = (char *)mp_obj_str_get_str(src);
response = ucloud_ai_url_decode(obj_src);
if (!response)
return mp_const_none;
mp_obj_t obj_decoded = mp_obj_new_strn(response);
return obj_decoded;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_obj_url_decode, obj_url_decode);
// this is the actual C-structure for our new object
STATIC const mp_rom_map_elem_t ucloud_ai_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ucloud_ai) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_getTokenId), MP_ROM_PTR(&mp_obj_get_token_id) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_computeMD5), MP_ROM_PTR(&mp_obj_compute_md5) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_generateUUID), MP_ROM_PTR(&mp_obj_generate_uuid) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_urlEncode), MP_ROM_PTR(&mp_obj_url_encode) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_urlDecode), MP_ROM_PTR(&mp_obj_url_decode) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ChatBot), MP_ROM_PTR(&chatbot_type) },
};
STATIC MP_DEFINE_CONST_DICT(ucloud_ai_locals_dict, ucloud_ai_locals_dict_table);
const mp_obj_module_t ucloud_ai_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&ucloud_ai_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_ucloud_ai, ucloud_ai_module, MICROPY_PY_UCLOUD_AI);
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/ucloud_ai/moducloud_ai.c | C | apache-2.0 | 3,922 |
#include <aos/kernel.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_UGRAPHICS
#include "py/builtin.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "ugraphics.h"
#include "ulog/ulog.h"
#define LOG_TAG "ugraphics"
STATIC mp_obj_t mp_ugraphics_init(size_t n_args, const mp_obj_t *args)
{
if (n_args < 2) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t width = 0;
int32_t height = 0;
width = mp_obj_get_int(args[0]);
height = mp_obj_get_int(args[1]);
mp_int_t status = ugraphics_init(width, height);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_init_obj, 2, mp_ugraphics_init);
STATIC mp_obj_t mp_ugraphics_deinit(size_t n_args, const mp_obj_t *args)
{
ugraphics_quit();
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_deinit_obj, 0, mp_ugraphics_deinit);
STATIC mp_obj_t mp_ugraphics_loadFont(size_t n_args, const mp_obj_t *args)
{
if (n_args < 2) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t size = 0;
char *path = (char *)mp_obj_str_get_str(args[0]);
size = mp_obj_get_int(args[1]);
mp_int_t status = ugraphics_load_font(path, size);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_loadFont_obj, 2, mp_ugraphics_loadFont);
STATIC mp_obj_t mp_ugraphics_setFontSytle(size_t n_args, const mp_obj_t *args)
{
if (n_args < 1) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t style = 0;
style = mp_obj_get_int(args[0]);
ugraphics_set_font_style(style);
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_setFontSytle_obj, 1, mp_ugraphics_setFontSytle);
STATIC mp_obj_t mp_ugraphics_ugraphicsFlip(size_t n_args, const mp_obj_t *args)
{
ugraphics_flip();
return mp_obj_new_int(0);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_ugraphicsFlip_obj, 0, mp_ugraphics_ugraphicsFlip);
STATIC mp_obj_t mp_ugraphics_ugraphicsClear(size_t n_args, const mp_obj_t *args)
{
mp_int_t status = ugraphics_clear();
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_ugraphicsClear_obj, 0, mp_ugraphics_ugraphicsClear);
STATIC mp_obj_t mp_ugraphics_setColour(size_t n_args, const mp_obj_t *args)
{
if (n_args < 1) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t colour = 0;
colour = mp_obj_get_int(args[0]);
mp_int_t status = ugraphics_set_color(colour);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_setColour_obj, 1, mp_ugraphics_setColour);
STATIC mp_obj_t mp_ugraphics_drawRect(size_t n_args, const mp_obj_t *args)
{
if (n_args < 4) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t x = 0;
int32_t y = 0;
int32_t w = 0;
int32_t h = 0;
x = mp_obj_get_int(args[0]);
y = mp_obj_get_int(args[1]);
w = mp_obj_get_int(args[2]);
h = mp_obj_get_int(args[3]);
mp_int_t status = ugraphics_draw_rect(x, y, w, h);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_drawRect_obj, 4, mp_ugraphics_drawRect);
STATIC mp_obj_t mp_ugraphics_fillRect(size_t n_args, const mp_obj_t *args)
{
if (n_args < 4) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t x = 0;
int32_t y = 0;
int32_t w = 0;
int32_t h = 0;
x = mp_obj_get_int(args[0]);
y = mp_obj_get_int(args[1]);
w = mp_obj_get_int(args[2]);
h = mp_obj_get_int(args[3]);
mp_int_t status = ugraphics_fill_rect(x, y, w, h);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_fillRect_obj, 4, mp_ugraphics_fillRect);
STATIC mp_obj_t mp_ugraphics_drawLine(size_t n_args, const mp_obj_t *args)
{
if (n_args < 4) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t x1 = 0;
int32_t y1 = 0;
int32_t x2 = 0;
int32_t y2 = 0;
x1 = mp_obj_get_int(args[0]);
y1 = mp_obj_get_int(args[1]);
x2 = mp_obj_get_int(args[2]);
y2 = mp_obj_get_int(args[3]);
mp_int_t status = ugraphics_draw_line(x1, y1, x2, y2);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_drawLine_obj, 4, mp_ugraphics_drawLine);
STATIC mp_obj_t mp_ugraphics_drawString(size_t n_args, const mp_obj_t *args)
{
if (n_args < 3) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t x = 0;
int32_t y = 0;
char *string = (char *)mp_obj_str_get_str(args[0]);
x = mp_obj_get_int(args[1]);
y = mp_obj_get_int(args[2]);
mp_int_t status = ugraphics_draw_string(string, x, y);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_drawString_obj, 3, mp_ugraphics_drawString);
STATIC mp_obj_t mp_ugraphics_stringWidth(size_t n_args, const mp_obj_t *args)
{
if (n_args < 1) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
char *string = (char *)mp_obj_str_get_str(args[0]);
mp_int_t ret = ugraphics_string_width(string);
return mp_obj_new_int(ret);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_stringWidth_obj, 1, mp_ugraphics_stringWidth);
STATIC mp_obj_t mp_ugraphics_saveImage(size_t n_args, const mp_obj_t *args)
{
if (n_args < 3) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t len = 0;
len = mp_obj_get_int(args[1]);
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_WRITE);
if (bufinfo.len < len * sizeof(uint16_t)) {
mp_raise_msg(&mp_type_ValueError, MP_ERROR_TEXT("bytearray size should not smaller than "
"twice of reg_quantity"));
return mp_const_none;
}
char *path = (char *)mp_obj_str_get_str(args[2]);
mp_int_t status = ugraphics_save_image(bufinfo.buf, len, path);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_saveImage_obj, 3, mp_ugraphics_saveImage);
STATIC mp_obj_t mp_ugraphics_drawImage(size_t n_args, const mp_obj_t *args)
{
if (n_args < 3) {
mp_raise_OSError(EINVAL);
return mp_const_none;
}
int32_t x = 0;
int32_t y = 0;
char *path = (char *)mp_obj_str_get_str(args[0]);
x = mp_obj_get_int(args[1]);
y = mp_obj_get_int(args[2]);
mp_int_t status = ugraphics_draw_image(path, x, y);
return MP_OBJ_NEW_SMALL_INT(-status);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(mp_ugraphics_drawImage_obj, 3, mp_ugraphics_drawImage);
STATIC const mp_rom_map_elem_t ugraphics_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ugraphics) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_init), MP_ROM_PTR(&mp_ugraphics_init_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mp_ugraphics_deinit_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_loadFont), MP_ROM_PTR(&mp_ugraphics_loadFont_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_setFontStyle), MP_ROM_PTR(&mp_ugraphics_setFontSytle_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ugraphicsFlip), MP_ROM_PTR(&mp_ugraphics_ugraphicsFlip_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_ugraphicsClear), MP_ROM_PTR(&mp_ugraphics_ugraphicsClear_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_setColour), MP_ROM_PTR(&mp_ugraphics_setColour_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_drawRect), MP_ROM_PTR(&mp_ugraphics_drawRect_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_fillRect), MP_ROM_PTR(&mp_ugraphics_fillRect_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_drawLine), MP_ROM_PTR(&mp_ugraphics_drawLine_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_drawString), MP_ROM_PTR(&mp_ugraphics_drawString_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_stringWidth), MP_ROM_PTR(&mp_ugraphics_stringWidth_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_saveImage), MP_ROM_PTR(&mp_ugraphics_saveImage_obj) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_drawImage), MP_ROM_PTR(&mp_ugraphics_drawImage_obj) },
};
STATIC MP_DEFINE_CONST_DICT(ugraphics_module_globals, ugraphics_module_globals_table);
const mp_obj_module_t ugraphics_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&ugraphics_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_ugraphics, ugraphics_module, MICROPY_PY_UGRAPHICS);
#endif // MICROPY_PY_UGRAPHICS
| YifuLiu/AliOS-Things | components/py_engine/modules/ugraphics/modugraphics.c | C | apache-2.0 | 8,493 |
/*
* Copyright (C) 2015-2019 Alibaba Group Holding Limited
*/
#if MICROPY_PY_ULOG
#include "py/builtin.h"
#include "py/obj.h"
#include "py/runtime.h"
#include "py/stackctrl.h"
#include "py_defines.h"
#include "ulog/ulog.h"
#define MOD_STR "LOG"
#define LOG_LEVEL_DEBUG "debug"
#define LOG_LEVEL_INFO "info"
#define LOG_LEVEL_WARN "warning"
#define LOG_LEVEL_ERROR "error"
#define LOG_LEVEL_FATAL "fatal"
#define LOG_LEVEL_NONE "none"
static mp_obj_t set_stdlog_level(mp_obj_t loglevel)
{
int ret = 0;
aos_log_level_t log_level;
log_level = mp_obj_get_int(loglevel);
ret = aos_set_log_level(log_level);
return mp_obj_new_int(ret);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_set_stdlog_level, set_stdlog_level);
#if ULOG_POP_CLOUD_ENABLE
static mp_obj_t set_popcloud_log_level(mp_obj_t loglevel)
{
int ret = 0;
aos_log_level_t log_level;
log_level = mp_obj_get_int(loglevel);
ret = aos_set_popcloud_log_level(log_level);
return mp_obj_new_int(ret);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_set_popcloud_log_level, set_popcloud_log_level);
#endif
#if ULOG_POP_CLOUD_ENABLE
static mp_obj_t set_popfs_log_level(mp_obj_t loglevel)
{
int ret = 0;
aos_log_level_t log_level;
log_level = mp_obj_get_int(loglevel);
ret = aos_set_popfs_log_level(log_level);
return mp_obj_new_int(ret);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_set_popfs_log_level, set_popfs_log_level);
static mp_obj_t set_log_file_path(mp_obj_t logpath)
{
int ret = 0;
const char *path = mp_obj_str_get_str(logpath);
if (NULL == path) {
amp_warn(MOD_STR, "invalid parameter\n");
return mp_obj_new_int(-1);
}
ret = ulog_fs_log_file_path(path);
if (ret) {
amp_warn(MOD_STR, "fail to set log file path %s\n", path);
return mp_obj_new_int(-1);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_set_log_file_path, set_log_file_path);
static mp_obj_t set_log_file_size(mp_obj_t logsize)
{
int ret = -1;
unsigned int filesize = 0;
filesize = mp_obj_get_int(logsize);
ret = ulog_fs_log_file_size(filesize);
if (ret) {
amp_error(MOD_STR, "fail to set log file size %d\n", filesize);
return mp_obj_new_int(-1);
}
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_1(native_set_log_file_size, set_log_file_size);
#endif
static mp_obj_t debug_log_out(mp_obj_t log_str, mp_obj_t log)
{
const char *msg = mp_obj_str_get_str(log);
const char *tag = mp_obj_str_get_str(log_str);
if (NULL == msg) {
amp_error(MOD_STR, "ulog fail to get output format msg");
return mp_obj_new_int(-1);
}
ulog(AOS_LL_DEBUG, tag, NULL, 0, "%s\n", msg);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_debug_log_out, debug_log_out);
static mp_obj_t info_log_out(mp_obj_t log_str, mp_obj_t log)
{
const char *msg = mp_obj_str_get_str(log);
const char *tag = mp_obj_str_get_str(log_str);
if (NULL == msg) {
amp_error(MOD_STR, "ulog fail to get output format msg");
return mp_obj_new_int(-1);
}
ulog(AOS_LL_INFO, tag, NULL, 0, "%s\n", msg);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_info_log_out, info_log_out);
static mp_obj_t warn_log_out(mp_obj_t log_str, mp_obj_t log)
{
const char *msg = mp_obj_str_get_str(log);
const char *tag = mp_obj_str_get_str(log_str);
if (NULL == msg) {
amp_error(MOD_STR, "ulog fail to get output format msg");
return mp_obj_new_int(-1);
}
ulog(AOS_LL_WARN, tag, NULL, 0, "%s\n", msg);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_warn_log_out, warn_log_out);
static mp_obj_t error_log_out(mp_obj_t log_str, mp_obj_t log)
{
const char *msg = mp_obj_str_get_str(log);
const char *tag = mp_obj_str_get_str(log_str);
if (NULL == msg) {
amp_error(MOD_STR, "ulog fail to get output format msg");
return mp_obj_new_int(-1);
}
ulog(AOS_LL_ERROR, tag, NULL, 0, "%s\n", msg);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_error_log_out, error_log_out);
static mp_obj_t fatal_log_out(mp_obj_t log_str, mp_obj_t log)
{
const char *msg = mp_obj_str_get_str(log);
const char *tag = mp_obj_str_get_str(log_str);
if (NULL == msg) {
amp_error(MOD_STR, "ulog fail to get output format msg");
return mp_obj_new_int(-1);
}
ulog(AOS_LL_FATAL, tag, NULL, 0, "%s\n", msg);
return mp_obj_new_int(0);
}
MP_DEFINE_CONST_FUN_OBJ_2(native_fatal_log_out, fatal_log_out);
STATIC const mp_rom_map_elem_t ulog_module_globals_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ulog) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_debug), MP_ROM_PTR(&native_debug_log_out) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_info), MP_ROM_PTR(&native_info_log_out) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_warn), MP_ROM_PTR(&native_warn_log_out) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_error), MP_ROM_PTR(&native_error_log_out) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_fatal), MP_ROM_PTR(&native_fatal_log_out) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_stdloglevel), MP_ROM_PTR(&native_set_stdlog_level) },
#if ULOG_POP_CLOUD_ENABLE
{ MP_OBJ_NEW_QSTR(MP_QSTR_cloudloglevel), MP_ROM_PTR(&native_set_popcloud_log_level) },
#endif
#if ULOG_POP_FS_ENABLE
{ MP_OBJ_NEW_QSTR(MP_QSTR_fsloglevel), MP_ROM_PTR(&native_set_popfs_log_level) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_setlogfilepath), MP_ROM_PTR(&native_set_log_file_path) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_setlogfilesize), MP_ROM_PTR(&native_set_log_file_size) },
#endif
{ MP_OBJ_NEW_QSTR(MP_QSTR_LOG_DEBUG), MP_ROM_INT(AOS_LL_DEBUG) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_LOG_INFO), MP_ROM_INT(AOS_LL_INFO) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_LOG_WARN), MP_ROM_INT(AOS_LL_WARN) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_LOG_ERROR), MP_ROM_INT(AOS_LL_ERROR) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_LOG_FATAL), MP_ROM_INT(AOS_LL_FATAL) },
};
STATIC MP_DEFINE_CONST_DICT(ulog_module_globals, ulog_module_globals_table);
const mp_obj_module_t ulog_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&ulog_module_globals,
};
MP_REGISTER_MODULE(MP_QSTR_ulog, ulog_module, MICROPY_PY_ULOG);
#endif // MICROPY_PY_ULOG
| YifuLiu/AliOS-Things | components/py_engine/modules/ulog/modulog.c | C | apache-2.0 | 6,217 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include "HaasLog.h"
#include "ak_common.h"
#include "ak_common_video.h"
#include "ak_log.h"
#include "ak_mem.h"
#include "ak_thread.h"
#include "ak_venc.h"
#include "ak_vi.h"
#include "ak_vpss.h"
#include "camera_ioctl.h"
#include "dev_info.h"
#include "minIni.h"
#include "os_drv.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/nlr.h"
#include "py/objlist.h"
#include "py/objstr.h"
#include "py/runtime.h"
#include "py/runtime0.h"
#include "py/stream.h"
#include "usb_s_uvc_ioctl.h"
#include "videocommon.h"
#define ISP_USE_DMA (0)
#define ISP_CFG_FILE "/etc/config/anyka_app.ini"
struct camera_ctx_t {
int main_width;
int main_height;
int sub_width;
int sub_height;
int media_type;
int codec;
};
static struct camera_ctx_t cctx = {
.main_width = CAMERA_MAIN_CHN_DEFAULT_WIDTH,
.main_height = CAMERA_MAIN_CHN_DEFAULT_HEIGHT,
.sub_width = CAMERA_SUB_CHN_DEFAULT_WIDTH,
.sub_height = CAMERA_SUB_CHN_DEFAULT_HEIGHT,
.codec = -1,
.media_type = VIDEO_MEDIA_TYPE_YUV,
};
#if ISP_USE_DMA
static int dma_pool_init(void)
{
int vi_dma_size = 14336; // 18406, unit in KB
int venc_dma_size = 12288; // 12000, unit in KB
int osd_dma_size = 300 << 10;
ak_mem_dma_pool_create(MODULE_ID_VI,
vi_dma_size << 10); /* 300KB left for OSD and audio*/
ak_mem_dma_pool_create(MODULE_ID_VENC, venc_dma_size << 10);
ak_mem_dma_pool_create(MODULE_ID_OSD, osd_dma_size);
ak_mem_dma_pool_activate();
return 0;
}
#endif
static int get_isp_cfg_path(int dev, char *buf, int size)
{
if (dev) {
ini_gets("isp_cfg", "isp_path_b", 0, buf, size, ISP_CFG_FILE);
} else {
ini_gets("isp_cfg", "isp_path_a", 0, buf, size, ISP_CFG_FILE);
}
return 0;
}
static int get_isp_ae_init_para(struct vpss_isp_ae_init_info *ae_init_info)
{
ae_init_info->d_gain = ini_getl("isp_cfg", "d_gain", 0, ISP_CFG_FILE);
ae_init_info->a_gain = ini_getl("isp_cfg", "a_gain", 0, ISP_CFG_FILE);
ae_init_info->exp_time = ini_getl("isp_cfg", "exp_time", 0, ISP_CFG_FILE);
ae_init_info->isp_d_gain =
ini_getl("isp_cfg", "isp_d_gain", 0, ISP_CFG_FILE);
return 0;
}
static int camera_set_ircut(int fd, int status_level)
{
int ret = 0;
int mode = IRCUT_MODE_DAY;
int feed_status = CAMERA_IRFEED_GPIO_STATUS_DAY;
if (status_level != 0) {
feed_status = CAMERA_IRFEED_GPIO_STATUS_NIGHT;
mode = IRCUT_MODE_NIGHT;
}
ret |= ioctl(fd, IO_CAMERA_IRCUT_GPIO_SET, &mode);
ret |= ioctl(fd, IO_CAMERA_IRFEED_GPIO_SET, &feed_status);
return ret;
}
static int vi_para_init(int camera_idx, int frame_rate)
{
int ircut_level = 0; // 0:day, 1:night
enum ak_vi_daynight_mode mode = VI_MODE_DAY_OUTDOOR;
int frame_depth = 2;
int data_type = VI_DATA_TYPE_YUV420SP;
if (cctx.media_type == VIDEO_MEDIA_TYPE_YUV) {
data_type = VI_DATA_TYPE_YUV420P;
}
/*
* step 1: open video input device
*/
if (ak_vi_open(camera_idx) != 0) {
LOG_E("%s, open vi dev(%d) fail\n", __func__, camera_idx);
return -1;
}
#if !QUICK_START
/*
* step 2: load isp config
*/
char isp_cfg_path[128];
if (get_isp_cfg_path(camera_idx, isp_cfg_path, sizeof(isp_cfg_path)) != 0) {
LOG_E("%s, get dev(%d) isp cfg fail\n", __func__, camera_idx);
ak_vi_close(camera_idx);
return -1;
}
if (ak_vi_load_sensor_cfg(camera_idx, isp_cfg_path) != 0) {
LOG_E("%s, load vi dev(%d) sensor cfg fail\n", __func__, camera_idx);
ak_vi_close(camera_idx);
return -1;
}
// get ae info from sensor
struct vpss_isp_ae_init_info ae_init_info;
ak_vpss_get_sensor_ae_info(camera_idx, &ae_init_info);
if (ae_init_info.exp_time == 0) {
// load init ae info
get_isp_ae_init_para(&ae_init_info);
}
// set ae info to isp
ak_vpss_set_ae_init_info(camera_idx, &ae_init_info);
/*
* step 3: set isp work mode
*/
if (mode == VI_MODE_NIGHTTIME) {
ircut_level = 1;
}
const char *ircut_dev[2] = { "/dev/ircut", "/dev/ircut1" };
int fd = open(ircut_dev[camera_idx], O_RDWR);
camera_set_ircut(fd, ircut_level);
close(fd);
ak_vi_switch_mode(camera_idx, mode);
#endif
/*
* step 4: get sensor support max resolution
*/
RECTANGLE_S res; // max sensor resolution
if (ak_vi_get_sensor_resolution(camera_idx, &res) != 0) {
LOG_E("%s, get vi dev(%d) sensor resolution fail\n", __func__,
camera_idx);
ak_vi_close(camera_idx);
return -1;
}
/*
* step 5: set vi working parameters
* default parameters: 20fps, day mode, auto frame-control
*/
VI_DEV_ATTR dev_attr;
memset(&dev_attr, 0, sizeof(dev_attr));
dev_attr.dev_id = camera_idx;
dev_attr.crop.left = 0;
dev_attr.crop.top = 0;
dev_attr.crop.width = res.width;
dev_attr.crop.height = res.height;
dev_attr.max_width = cctx.main_width;
dev_attr.max_height = cctx.main_height;
dev_attr.data_type = data_type;
dev_attr.sub_max_width = cctx.sub_width;
dev_attr.sub_max_height = cctx.sub_height;
dev_attr.frame_rate = frame_rate;
if (ak_vi_set_dev_attr(camera_idx, &dev_attr) != 0) {
LOG_E("%s, set vi dev(%d) dev attr fail\n", __func__, camera_idx);
ak_vi_close(camera_idx);
return -1;
}
/*
* step 5: set channel attribute
*/
// ak_print_normal_ex(MODULE_ID_VI, "vi device set main channel\n");
VI_CHN_ATTR chn_attr;
memset(&chn_attr, 0, sizeof(chn_attr));
chn_attr.chn_id = VIDEO_CHN0;
chn_attr.res.width = cctx.main_width;
chn_attr.res.height = cctx.main_height;
chn_attr.frame_depth = frame_depth;
chn_attr.frame_rate = frame_rate;
if (ak_vi_set_chn_attr(VIDEO_CHN0, &chn_attr) != 0) {
LOG_E("%s, set vi dev(%d) chn0 attr fail\n", __func__, camera_idx);
ak_vi_close(camera_idx);
return -1;
}
memset(&chn_attr, 0, sizeof(chn_attr));
chn_attr.chn_id = VIDEO_CHN1;
chn_attr.res.width = cctx.sub_width;
chn_attr.res.height = cctx.sub_height;
chn_attr.frame_depth = frame_depth;
chn_attr.frame_rate = frame_rate;
if (ak_vi_set_chn_attr(VIDEO_CHN1, &chn_attr) != 0) {
LOG_E("%s, set vi dev(%d) chn1 attr fail\n", __func__, camera_idx);
ak_vi_close(camera_idx);
return -1;
}
/*
* step 6: enable vi channel
*/
if (ak_vi_enable_chn(VIDEO_CHN0) != 0) {
LOG_E("%s, enable vi dev(%d) chn0 attr fail\n", __func__, camera_idx);
ak_vi_close(camera_idx);
return -1;
}
if (ak_vi_enable_chn(VIDEO_CHN1) != 0) {
LOG_E("%s, enable vi dev(%d) chn1 attr fail\n", __func__, camera_idx);
ak_vi_disable_chn(VIDEO_CHN0);
ak_vi_close(camera_idx);
return -1;
}
return 0;
}
int py_video_camera_open(int camera_idx, int frame_rate)
{
do {
cctx.codec = -1;
sdk_run_config config;
memset(&config, 0, sizeof(config));
config.mem_trace_flag = SDK_RUN_NORMAL;
if (ak_sdk_init(&config) != 0)
break;
/* LOG_LEVEL_NORMAL for debug */
// ak_print_set_level(MODULE_ID_ALL, LOG_LEVEL_ERROR);
// ak_print_set_syslog_level(MODULE_ID_ALL, LOG_LEVEL_ERROR);
ak_print_set_level(MODULE_ID_ALL, LOG_LEVEL_NORMAL);
ak_print_set_syslog_level(MODULE_ID_ALL, LOG_LEVEL_NORMAL);
#if ISP_USE_DMA
dma_pool_init();
#endif
if (vi_para_init(camera_idx, frame_rate) != 0)
break;
if (ak_vi_enable_dev(camera_idx) != 0) {
ak_vi_disable_chn(VIDEO_CHN0);
ak_vi_disable_chn(VIDEO_CHN1);
ak_vi_close(camera_idx);
LOG_E("%s, enable vi dev(%d) fail\n", __func__, camera_idx);
break;
}
return 0;
} while (0);
/* process failure of sdk */
#if ISP_USE_DMA
ak_mem_dma_pool_exit();
#endif
ak_sdk_exit();
return -1;
}
int py_video_camera_close(int camera_idx)
{
ak_vi_disable_chn(VIDEO_CHN0);
ak_vi_disable_chn(VIDEO_CHN1);
ak_vi_disable_dev(camera_idx);
ak_vi_close(camera_idx);
#if ISP_USE_DMA
ak_mem_dma_pool_exit();
#endif
if (cctx.codec >= 0) {
ak_venc_close(cctx.codec);
cctx.codec = -1;
}
ak_sdk_exit();
return 0;
}
int py_video_camera_frame_get(isp_frame_t *frame)
{
if (ak_vi_get_frame(VIDEO_CHN0, frame) != 0) {
LOG_E("%s, get frame fail\n", __func__);
return -1;
}
return 0;
}
int py_video_camera_frame_release(isp_frame_t *frame)
{
ak_vi_release_frame(VIDEO_CHN0, frame);
return 0;
}
static int save_data(const char *path, const char *extension, char *buf,
unsigned int len)
{
FILE *fd = NULL;
struct ak_date date;
char time_str[32] = { 0 };
char file_path[64] = { 0 };
/* construct file name */
ak_get_localdate(&date);
ak_date_to_string(&date, time_str);
snprintf(file_path, sizeof(file_path), "/mnt/sdcard/%s_%s.%s", path,
time_str, extension);
/*
* open appointed file to save YUV data
* save main channel yuv here
*/
fd = fopen(file_path, "wb+");
if (fd == NULL) {
LOG_E("%s, save file fail, fd:%d\n", __func__, fd);
return -1;
}
do {
len -= fwrite(buf, 1, len, fd);
} while (len != 0);
fclose(fd);
return 0;
}
int py_video_camera_config_set(int width, int height, int media_type)
{
int ret = 0;
if (cctx.media_type != media_type) {
cctx.media_type = media_type;
ret = 1;
}
if (height != 0 && cctx.main_height != height) {
cctx.main_height = height;
ret = 1;
}
if (width != 0 && cctx.main_width != width) {
cctx.main_width = width;
ret = 1;
}
return ret;
}
int py_video_camera_config_get(int *width, int *height, int *media_type)
{
if (width)
*width = cctx.main_width;
if (height)
*height = cctx.main_height;
if (media_type)
*media_type = cctx.media_type;
return 0;
}
int py_video_camera_save(isp_frame_t *frame, int pic_type, const char *path)
{
int ret;
if (pic_type != VIDEO_MEDIA_TYPE_YUV) {
struct video_stream video_str;
if (cctx.codec < 0) {
cctx.codec =
py_venc_init(cctx.main_width, cctx.main_height, 1, pic_type);
if (cctx.codec < 0) {
LOG_E("%s, open venc fail, fd:%d\n", __func__, cctx.codec);
return -1;
;
}
}
memset(&video_str, 0, sizeof(video_str));
ret = ak_venc_encode_frame(cctx.codec, frame->vi_frame.data,
frame->vi_frame.len, NULL, &video_str);
if (ret) {
ak_venc_close(cctx.codec);
cctx.codec = -1;
LOG_E("%s, encode fail, ret:%d\n", __func__, ret);
return -1;
}
ret = save_data(path, "jpg", video_str.data, video_str.len);
ak_venc_release_stream(cctx.codec, &video_str);
} else {
ret = save_data(path, "yuv", frame->vi_frame.data, frame->vi_frame.len);
}
return ret;
} | YifuLiu/AliOS-Things | components/py_engine/modules/video/ak_camera.c | C | apache-2.0 | 11,382 |
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "HaasLog.h"
#include "ak_common.h"
#include "ak_common_video.h"
#include "ak_venc.h"
#include "ak_vi.h"
#include "ak_vpss.h"
#include "dev_info.h"
#include "minIni.h"
#include "usb_s_uvc_ioctl.h"
#include "videocommon.h"
#define UVC_ENC_CONFIG_FILE "/etc/config/anyka_app.ini"
int py_venc_init(int width, int height, int fps, int media_type)
{
int ret = -1, handle_id = -1;
struct venc_param param;
param.width = width;
param.height = height;
param.fps = fps;
param.goplen = fps * 2;
param.target_kbps = 1024;
param.max_kbps = 1024;
param.br_mode = BR_MODE_CBR;
param.minqp = 25;
param.maxqp = 48;
param.initqp = (param.minqp + param.maxqp) >> 1;
param.chroma_mode = CHROMA_4_2_0;
param.max_picture_size = 0;
param.enc_level = 41;
param.smart_mode = 0;
param.smart_goplen = 100;
param.smart_quality = 50;
param.smart_static_value = 0;
param.jpeg_qlevel = JPEG_QLEVEL_DEFAULT;
param.smart_static_value = 550;
if (VIDEO_MEDIA_TYPE_JPEG == media_type) {
param.minqp =
ini_getl("usbcam", "mjpeg_minqp", 50, UVC_ENC_CONFIG_FILE);
param.maxqp =
ini_getl("usbcam", "mjpeg_maxqp", 50, UVC_ENC_CONFIG_FILE);
param.max_kbps =
ini_getl("usbcam", "mjpeg_kbps", 1024, UVC_ENC_CONFIG_FILE);
param.target_kbps =
ini_getl("usbcam", "mjpeg_kbps", 1024, UVC_ENC_CONFIG_FILE);
param.profile = PROFILE_JPEG;
param.enc_out_type = MJPEG_ENC_TYPE;
} else if (VIDEO_MEDIA_TYPE_H264 == media_type) {
param.minqp = ini_getl("usbcam", "h264_minqp", 25, UVC_ENC_CONFIG_FILE);
param.maxqp = ini_getl("usbcam", "h264_maxqp", 48, UVC_ENC_CONFIG_FILE);
param.max_kbps =
ini_getl("usbcam", "h264_kbps", 1024, UVC_ENC_CONFIG_FILE);
param.target_kbps =
ini_getl("usbcam", "h264_kbps", 1024, UVC_ENC_CONFIG_FILE);
param.profile = PROFILE_MAIN;
param.enc_out_type = H264_ENC_TYPE;
} else {
param.minqp = ini_getl("usbcam", "hevc_minqp", 25, UVC_ENC_CONFIG_FILE);
param.maxqp = ini_getl("usbcam", "hevc_maxqp", 50, UVC_ENC_CONFIG_FILE);
param.max_kbps =
ini_getl("usbcam", "hevc_kbps", 1024, UVC_ENC_CONFIG_FILE);
param.target_kbps =
ini_getl("usbcam", "hevc_kbps", 1024, UVC_ENC_CONFIG_FILE);
param.profile = PROFILE_HEVC_MAIN;
param.enc_out_type = HEVC_ENC_TYPE;
}
ret = ak_venc_open(¶m, &handle_id);
if (ret || -1 == handle_id) {
LOG_E("%s, enc open fail(id:%d, ret:%d)\r\n", __func__, ret, handle_id);
return ret;
}
return handle_id;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/video/ak_codec.c | C | apache-2.0 | 2,826 |
#include "ak_rtsp.h"
#include <fcntl.h>
#include <kernel.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include "HaasLog.h"
#include "ak_common.h"
#include "ak_common_video.h"
#include "ak_log.h"
#include "ak_mem.h"
#include "ak_thread.h"
#include "ak_venc.h"
#include "ak_vi.h"
#include "ak_video.h"
#include "ak_vpss.h"
#include "camera_ioctl.h"
#include "dev_info.h"
#include "videocommon.h"
#define RTSP_STREAM_TASK_STACK_SIZE (32 * 1024)
#define RTSP_CHAN_NUM_MAX (RTSP_CHUNNEL_1 + 1)
#define RTSP_THREAD_PRIORITY (60)
#define RTSP_DEFAULT_FPS (25)
enum PY_RTSP_STATE_T {
RTSP_STATE_CLOSE,
RTSP_STATE_READY,
RTSP_STATE_WORK,
};
struct rtsp_video_thread_attr {
ak_pthread_t thread_id;
char *thread_name;
int vi_channel_id;
enum rtsp_chunnel_type rtsp_channel;
};
struct rtsp_ctrl {
int fps;
int camera_idx;
int media_type;
char *url;
char *save_path;
enum PY_RTSP_STATE_T chan_state[RTSP_CHAN_NUM_MAX];
struct rtsp_video_thread_attr *attr;
};
/******************************************************
* Global Variables
******************************************************/
static struct rtsp_ctrl g_rtsp_ctrl = {
.fps = RTSP_DEFAULT_FPS,
.camera_idx = -1,
.media_type = VIDEO_MEDIA_TYPE_H264,
.url = NULL,
.save_path = NULL,
.attr = NULL,
};
/*
* @note: there are two channel concept.
* vi-channel refers to video data stream, one vi device has two related
* vi-channels. rtsp-channel refers to rtsp send data stream, rtsp module has
* two rtsp-channel, they are defined in <enum rtsp_chunnel_type> in "ak_rtsp.h"
* since there are two vi devices(sensor), we have 4 vi-channels, 2
* rtsp-channel total.
*
* @rtsp_video_thread: get vi stream and send to rtsp
* @param args[in]: rtsp channel which thread will relate to
* @return void *
*/
static void *rtsp_video_thread(void *arg)
{
struct rtsp_video_thread_attr *self = (struct rtsp_video_thread_attr *)arg;
int ret = -1;
int venc_handle = -1;
enum rtsp_frame_type frame_type;
char ifram_force = 1;
struct video_stream stream = { 0 };
unsigned long long gop_size = 0;
unsigned max_size = 0;
struct ak_timeval pre_tv;
struct ak_timeval cur_tv;
int width = CAMERA_SUB_CHN_DEFAULT_WIDTH;
int height = CAMERA_SUB_CHN_DEFAULT_HEIGHT;
FILE *save_fp = NULL;
char save_file[96] = { 0 };
ak_thread_set_name(self->thread_name);
if (self->rtsp_channel == RTSP_CHUNNEL_0) {
py_video_camera_config_get(&width, &height, NULL);
}
venc_handle =
py_venc_init(width, height, g_rtsp_ctrl.fps, g_rtsp_ctrl.media_type);
if (venc_handle < 0) {
LOG_E("video encode open failed!\n");
goto exit_thread;
}
APP_CHN_S Schn, Dchn;
Schn.mid = MODULE_ID_VI;
Schn.oid = self->vi_channel_id;
Dchn.mid = MODULE_ID_VENC;
Dchn.oid = self->rtsp_channel;
APP_BIND_PARAM param;
param.frame_rate = 0;
param.frame_depth = 100;
unsigned long kbps_r = 0;
unsigned int count = 0;
int bind_flag = 0;
while (1) {
/* iterate main and sub channel, get stream and set to rtsp */
while (RTSP_STATE_WORK == g_rtsp_ctrl.chan_state[self->rtsp_channel]) {
/* get stream until success */
if (ak_rtsp_get_chunnel_state(self->rtsp_channel) == 0) {
if (bind_flag == 0) {
bind_flag = 1;
ret = ak_app_video_bind_chn(&Schn, &Dchn, ¶m);
if (ret != AK_SUCCESS) {
LOG_E("ak_app_video_bind_chn failed [%d]\n", ret);
goto exit_venc;
}
ak_get_ostime(&pre_tv);
ak_get_ostime(&cur_tv);
ak_app_video_set_dst_chn_active(&Dchn, AK_TRUE);
}
if (ifram_force) {
ak_venc_request_idr(venc_handle);
ifram_force = 0;
}
} else {
ifram_force = 1;
if (bind_flag == 1) {
if (ak_app_video_venc_get_stream(&Dchn, &stream) == 0) {
ak_venc_release_stream(venc_handle, &stream);
} else {
ak_sleep_ms(10);
}
if (g_rtsp_ctrl.save_path) {
if (NULL != save_fp) {
fclose(save_fp);
save_fp = NULL;
count++;
}
}
} else {
ak_sleep_ms(200);
}
continue;
}
if (g_rtsp_ctrl.save_path) {
if (NULL == save_fp) {
snprintf(save_file, sizeof(save_file), "%s/chn%d_%d.%s",
g_rtsp_ctrl.save_path, self->rtsp_channel, count,
g_rtsp_ctrl.media_type == VIDEO_MEDIA_TYPE_H264
? "h264"
: "hevc");
save_fp = fopen(save_file, "w+");
if (save_fp == NULL) {
LOG_E("fopen %s failed\n", save_file);
return NULL;
}
}
}
memset(&stream, 0, sizeof(struct video_stream));
ret = ak_app_video_venc_get_stream(&Dchn, &stream);
if (ret == AK_SUCCESS) {
/* send stream */
if (FRAME_TYPE_I == stream.frame_type) {
frame_type = RTSP_IFRAME;
} else if (FRAME_TYPE_P == stream.frame_type) {
frame_type = RTSP_PFRAME;
}
ret = ak_rtsp_send_stream(self->rtsp_channel, frame_type,
stream.data, stream.len, stream.ts);
if (ret < 0) {
LOG_E("ak_rtsp_send_stream fail %d\n", ret);
}
if (g_rtsp_ctrl.save_path) {
if (stream.len > 0) {
if (fwrite(stream.data, stream.len, 1, save_fp) <= 0) {
LOG_E("fwrite %s failed!\n", save_file);
}
}
}
ak_venc_release_stream(venc_handle, &stream);
} else {
ak_sleep_ms(10);
}
}
if (RTSP_STATE_CLOSE == g_rtsp_ctrl.chan_state[self->rtsp_channel]) {
ak_app_video_unbind_chn(&Schn, &Dchn);
goto exit_venc;
}
ak_sleep_ms(30);
}
exit_venc:
ak_venc_close(venc_handle);
exit_thread:
ak_thread_exit();
return NULL;
}
static int rtsp_create_monitor_thread()
{
/* start rtsp_control, create two video threads for two RTSP channels */
struct rtsp_video_thread_attr *attr;
if (g_rtsp_ctrl.attr != NULL)
return 0;
attr = (struct rtsp_video_thread_attr *)malloc(
sizeof(struct rtsp_video_thread_attr) * RTSP_CHAN_NUM_MAX);
if (NULL == attr) {
LOG_E("malloc video thread attr failed.\n");
return -1;
}
// build main channel thread attribute
attr[RTSP_CHUNNEL_0].thread_name = "rtsp_main_video";
attr[RTSP_CHUNNEL_0].vi_channel_id = VIDEO_CHN_MAIN;
attr[RTSP_CHUNNEL_0].rtsp_channel = RTSP_CHUNNEL_0;
g_rtsp_ctrl.chan_state[RTSP_CHUNNEL_0] =
RTSP_STATE_WORK; // open audio rtsp main chan(defaut main chan)
// build sub channel thread attribute
attr[RTSP_CHUNNEL_1].thread_name = "rtsp_sub_video";
attr[RTSP_CHUNNEL_1].vi_channel_id = VIDEO_CHN_SUB;
attr[RTSP_CHUNNEL_1].rtsp_channel = RTSP_CHUNNEL_1;
g_rtsp_ctrl.chan_state[RTSP_CHUNNEL_1] =
RTSP_STATE_WORK; // open video rtsp sub chan for double chan use
if (ak_thread_create(&attr[RTSP_CHUNNEL_0].thread_id, rtsp_video_thread,
&attr[RTSP_CHUNNEL_0], RTSP_STREAM_TASK_STACK_SIZE,
RTSP_THREAD_PRIORITY) != 0) {
g_rtsp_ctrl.chan_state[RTSP_CHUNNEL_0] = RTSP_STATE_CLOSE;
g_rtsp_ctrl.chan_state[RTSP_CHUNNEL_1] = RTSP_STATE_CLOSE;
free(attr);
LOG_E("create client_listen main_chan thread error.\r\n");
return -1;
}
/* start sub video */
if (ak_thread_create(&attr[RTSP_CHUNNEL_1].thread_id, rtsp_video_thread,
&attr[RTSP_CHUNNEL_1], RTSP_STREAM_TASK_STACK_SIZE,
RTSP_THREAD_PRIORITY) != 0) {
g_rtsp_ctrl.chan_state[RTSP_CHUNNEL_0] = RTSP_STATE_CLOSE;
g_rtsp_ctrl.chan_state[RTSP_CHUNNEL_1] = RTSP_STATE_CLOSE;
ak_thread_join(attr[RTSP_CHUNNEL_0].thread_id);
free(attr);
LOG_E("create client_listen sub_chan thread error.\r\n");
return -1;
}
g_rtsp_ctrl.attr = attr;
return 0;
}
int py_rtsp_start(void)
{
char path[32];
if (RTSP_STATE_CLOSE == g_rtsp_ctrl.chan_state[0]) {
/* init rtsp */
if (ak_rtsp_init() != 0) {
LOG_E("init rtsp failed\n");
return -1;
}
/* init rtsp channel name,default name is camera-x,x: 1,2*/
if (g_rtsp_ctrl.url == NULL) {
strncpy(path, "main", sizeof(path));
} else {
snprintf(path, sizeof(path), "main/%s", g_rtsp_ctrl.url);
}
if (ak_rtsp_set_chunnel_name(RTSP_CHUNNEL_0, path) != 0) {
LOG_E("rtsp set chan_main name error\n");
ak_rtsp_deinit();
return -1;
}
if (g_rtsp_ctrl.url == NULL) {
strncpy(path, "sub", sizeof(path));
} else {
snprintf(path, sizeof(path), "sub/%s", g_rtsp_ctrl.url);
}
if (ak_rtsp_set_chunnel_name(RTSP_CHUNNEL_1, path) != 0) {
LOG_E("rtsp set chan_sub name error\n");
ak_rtsp_deinit();
return -1;
}
/* set rtsp video type */
enum rtsp_video_type rtsp_enc_type;
if (g_rtsp_ctrl.media_type == VIDEO_MEDIA_TYPE_HEVC) {
rtsp_enc_type = RTSP_VIDEO_H265;
} else {
rtsp_enc_type = RTSP_VIDEO_H264;
}
// for single steam, set both of channel rtsp type
ak_rtsp_set_video_type(RTSP_CHUNNEL_0, rtsp_enc_type);
ak_rtsp_set_video_type(RTSP_CHUNNEL_1, rtsp_enc_type);
/* start rtsp service */
ak_rtsp_start();
if (rtsp_create_monitor_thread() < 0) {
LOG_E("create rtsp main thread error\r\n");
ak_rtsp_stop();
ak_rtsp_deinit();
return -1;
}
} else {
LOG_W("rtsp state is not closed, can't be started!\n");
}
return 0;
}
int py_rtsp_open(int camera_idx, int media_type, int fps, const char *url)
{
if (g_rtsp_ctrl.camera_idx >= 0) {
py_rtsp_close();
}
if (g_rtsp_ctrl.camera_idx < 0) {
if (url && strlen(url) > 0) {
g_rtsp_ctrl.url = strdup(url);
if (g_rtsp_ctrl.url == NULL) {
LOG_E("rtsp alloc url fail\n");
return -1;
}
}
py_video_camera_config_set(0, 0, VIDEO_MEDIA_TYPE_H264);
if (py_video_camera_open(camera_idx, fps) != 0) {
LOG_E("vi dev[%d] init fail\n", camera_idx);
if (g_rtsp_ctrl.url) {
free(g_rtsp_ctrl.url);
g_rtsp_ctrl.url = NULL;
}
return -1;
}
g_rtsp_ctrl.camera_idx = camera_idx;
g_rtsp_ctrl.fps = fps;
g_rtsp_ctrl.media_type = media_type;
}
return 0;
}
int py_rtsp_stop(void)
{
if (RTSP_STATE_CLOSE != g_rtsp_ctrl.chan_state[0]) {
g_rtsp_ctrl.chan_state[0] = RTSP_STATE_CLOSE;
g_rtsp_ctrl.chan_state[1] = RTSP_STATE_CLOSE;
}
if (g_rtsp_ctrl.attr != NULL) {
ak_thread_join(g_rtsp_ctrl.attr[RTSP_CHUNNEL_0].thread_id);
ak_thread_join(g_rtsp_ctrl.attr[RTSP_CHUNNEL_1].thread_id);
ak_rtsp_stop();
free(g_rtsp_ctrl.attr);
g_rtsp_ctrl.attr = NULL;
}
return 0;
}
int py_rtsp_close(void)
{
py_rtsp_stop();
py_video_camera_close(g_rtsp_ctrl.camera_idx);
if (g_rtsp_ctrl.url) {
free(g_rtsp_ctrl.url);
g_rtsp_ctrl.url = NULL;
}
if (g_rtsp_ctrl.save_path) {
free(g_rtsp_ctrl.save_path);
g_rtsp_ctrl.save_path = NULL;
}
}
int py_rtsp_resume(void)
{
if (RTSP_STATE_READY == g_rtsp_ctrl.chan_state[0]) {
g_rtsp_ctrl.chan_state[0] = RTSP_STATE_WORK;
g_rtsp_ctrl.chan_state[1] = RTSP_STATE_WORK;
} else {
LOG_W("rtsp state is not ready, can't be resumed!\n");
}
return 0;
}
int py_rtsp_pause(void)
{
if (RTSP_STATE_WORK == g_rtsp_ctrl.chan_state[0]) {
g_rtsp_ctrl.chan_state[0] = RTSP_STATE_READY;
g_rtsp_ctrl.chan_state[1] = RTSP_STATE_READY;
} else {
LOG_W("rtsp state is not work, can't be paused!\n");
}
return 0;
} | YifuLiu/AliOS-Things | components/py_engine/modules/video/ak_rtsp.c | C | apache-2.0 | 13,217 |
#include <stdbool.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include "HaasLog.h"
#include "ak_common.h"
#include "ak_common_video.h"
#include "ak_log.h"
#include "ak_thread.h"
#include "ak_venc.h"
#include "ak_vi.h"
#include "ak_vpss.h"
#include "dev_info.h"
#include "list.h"
#include "minIni.h"
#include "os_drv.h"
#include "usb_s_uvc_ioctl.h"
#include "uvc.h"
#include "videocommon.h"
enum uvc_stream_state_t {
USBCAM_STATE_STOP = 0,
USBCAM_STATE_STANDBY = 1,
USBCAM_STATE_WORKING = 2,
};
typedef struct uvc_dev {
ak_pthread_t monitor_thread;
ak_pthread_t stream_thread;
ak_pthread_t ctrl_thread;
int uvc_fd;
int venc_fd;
int camera_idx;
int vi_chan;
int width;
int height;
int sensor_fps;
int out_fps;
int ext_process;
void (*ext_process_cb)(isp_frame_t *frame);
void (*ext_event_cb)(int start);
int stream_type;
enum ak_vi_daynight_mode day_night; // 0: day 1: night
enum uvc_stream_state_t send_stream;
char monitor;
char ctrl;
} uvc_dev_t;
typedef struct _uvc_msg_queue {
int ret;
struct list_head cmd_list;
} uvc_msg_queue;
struct list_head uvc_cmd_list;
static ak_sem_t uvc_ctrl_sem;
static ak_mutex_t uvc_ctrl_mutex;
static uvc_dev_t m_uvc_dev = {
.monitor_thread = NULL,
.ctrl_thread = NULL,
.stream_thread = NULL,
.camera_idx = VIDEO_DEV0,
.vi_chan = VIDEO_CHN0,
.venc_fd = -1,
.uvc_fd = -1,
.stream_type = UVC_DEFAULT_FORMAT,
.width = CAMERA_MAIN_CHN_DEFAULT_WIDTH,
.height = CAMERA_MAIN_CHN_DEFAULT_HEIGHT,
.day_night = VI_MODE_DAY_OUTDOOR,
.out_fps = CAMERA_DEFAULT_FPS,
.send_stream = USBCAM_STATE_STOP,
.ctrl = 0,
.monitor = 0,
.ext_process = 0,
.ext_process_cb = NULL,
.ext_event_cb = NULL,
};
static int usbcam_video_get_format(int *width, int *height,
enum uvc_stream_type *type)
{
if (ioctl(m_uvc_dev.uvc_fd, IO_UVC_GET_FORMAT, type) == -1) {
LOG_E("ioctl failed\n");
return -1;
}
if (ioctl(m_uvc_dev.uvc_fd, IO_UVC_GET_HEIGHT, height) == -1) {
LOG_E("ioctl failed\n");
return -1;
}
if (ioctl(m_uvc_dev.uvc_fd, IO_UVC_GET_WIDTH, width) == -1) {
LOG_E("ioctl failed\n");
return -1;
}
}
static int usbcam_video_open(void)
{
RECTANGLE_S res;
int fd = open(UVC_FILE, O_RDWR, 0);
if (fd == -1) {
LOG_E("uvc open failed,m_uvc_dev.uvc_fd:%d\n", fd);
return -1;
}
// max sensor resolution
if (ak_vi_get_sensor_resolution(m_uvc_dev.camera_idx, &res) != 0) {
LOG_E("%s, get vi dev(%d) sensor resolution fail\n", __func__,
m_uvc_dev.camera_idx);
close(fd);
return -1;
}
if (ioctl(fd, IO_UVC_SET_SENSOR_RES, &res) != 0) {
LOG_E("%s, set sensor resolution fail\n", __func__);
close(fd);
return -1;
}
if (ioctl(fd, IO_UVC_START_CTL, NULL) == -1) {
LOG_E("ioctl IO_UVC_START_CTL failed\n");
close(fd);
return -1;
}
return fd;
}
static int usbcam_video_uvc_wait_start(void)
{
return ioctl(m_uvc_dev.uvc_fd, IO_UVC_WAIT_START_CTL, NULL);
}
static int py_usbcam_video_stream_start(void)
{
int stream_type;
usbcam_video_get_format(&(m_uvc_dev.width), &(m_uvc_dev.height),
&stream_type);
switch (stream_type) {
case UVC_STREAM_YUV:
m_uvc_dev.stream_type = VIDEO_MEDIA_TYPE_YUV;
break;
case UVC_STREAM_MJPEG:
m_uvc_dev.stream_type = VIDEO_MEDIA_TYPE_JPEG;
break;
case UVC_STREAM_H264:
m_uvc_dev.stream_type = VIDEO_MEDIA_TYPE_H264;
break;
default:
m_uvc_dev.stream_type = VIDEO_MEDIA_TYPE_YUV;
break;
}
if (py_video_camera_config_set(m_uvc_dev.width, m_uvc_dev.height,
m_uvc_dev.stream_type) != 0) {
py_video_camera_close(m_uvc_dev.camera_idx);
py_video_camera_open(m_uvc_dev.camera_idx, m_uvc_dev.out_fps);
}
if (m_uvc_dev.ext_process) {
m_uvc_dev.out_fps = 2;
}
if (m_uvc_dev.stream_type != VIDEO_MEDIA_TYPE_YUV) {
m_uvc_dev.venc_fd =
py_venc_init(m_uvc_dev.width, m_uvc_dev.height, m_uvc_dev.out_fps,
m_uvc_dev.stream_type);
if (m_uvc_dev.venc_fd < 0) {
LOG_E("%s, venc init fail:%d\r\n", __func__, m_uvc_dev.venc_fd);
return -1;
;
}
}
m_uvc_dev.send_stream = USBCAM_STATE_WORKING;
return 0;
}
static void py_usbcam_video_stream_stop(void)
{
if (m_uvc_dev.send_stream) {
m_uvc_dev.send_stream = USBCAM_STATE_STANDBY;
if (m_uvc_dev.venc_fd >= 0) {
ak_venc_close(m_uvc_dev.venc_fd);
m_uvc_dev.venc_fd = -1;
}
}
}
static void usbcam_video_stream_send(void)
{
int ret;
int chan = m_uvc_dev.vi_chan;
struct video_stream video_str;
struct video_input_frame frame;
if (ak_vi_get_frame(chan, &frame) == AK_FAILED) {
LOG_E("get frame fail\r\n");
return;
}
if (m_uvc_dev.ext_process && m_uvc_dev.ext_process_cb != NULL) {
m_uvc_dev.ext_process_cb(&frame);
}
if (m_uvc_dev.stream_type != VIDEO_MEDIA_TYPE_YUV) {
memset(&video_str, 0, sizeof(video_str));
ret = ak_venc_encode_frame(m_uvc_dev.venc_fd, frame.vi_frame.data,
frame.vi_frame.len, NULL, &video_str);
ak_vi_release_frame(chan, &frame);
if (ret) {
LOG_E("encode fail\r\n");
return;
}
write(m_uvc_dev.uvc_fd, video_str.data, video_str.len);
ak_venc_release_stream(m_uvc_dev.venc_fd, &video_str);
} else {
write(m_uvc_dev.uvc_fd, frame.vi_frame.data, frame.vi_frame.len);
ak_vi_release_frame(chan, &frame);
}
}
static void *usbcam_video_monitor_thread(void *arg)
{
int ret;
fd_set readset;
struct timeval timeout;
uvc_msg_queue *pmsg;
timeout.tv_sec = 1;
timeout.tv_usec = 0;
while (m_uvc_dev.monitor) {
FD_ZERO(&readset);
FD_SET(m_uvc_dev.uvc_fd, &readset);
/* Wait for read or write */
ret = select(m_uvc_dev.uvc_fd + 1, &readset, NULL, NULL, &timeout);
if (ret == 0) {
// LOG_E("select timeout\r\n");
continue;
}
ret = usbcam_video_uvc_wait_start();
pmsg = (uvc_msg_queue *)malloc(sizeof(uvc_msg_queue));
if (pmsg) {
pmsg->ret = ret;
list_add_tail(&pmsg->cmd_list, &uvc_cmd_list);
ak_thread_sem_post(&uvc_ctrl_sem);
}
}
ak_thread_exit();
}
static void *usbcam_video_ctrl_thread(void *arg)
{
struct list_head *pos;
struct list_head *q;
uvc_msg_queue *pmsg;
while (m_uvc_dev.ctrl) {
if (ak_thread_sem_wait(&uvc_ctrl_sem) == 0) {
list_for_each_safe(pos, q, &uvc_cmd_list)
{
pmsg = list_entry(pos, uvc_msg_queue, cmd_list);
if (pmsg) {
ak_thread_mutex_lock(&uvc_ctrl_mutex);
if (pmsg->ret) {
if (m_uvc_dev.ext_process &&
m_uvc_dev.ext_event_cb != NULL) {
m_uvc_dev.ext_event_cb(1);
}
py_usbcam_video_stream_stop();
py_usbcam_video_stream_start();
} else {
py_usbcam_video_stream_stop();
if (m_uvc_dev.ext_process &&
m_uvc_dev.ext_event_cb != NULL) {
m_uvc_dev.ext_event_cb(0);
}
}
ak_thread_mutex_unlock(&uvc_ctrl_mutex);
}
list_del(pos);
if (pmsg)
free(pmsg);
}
}
}
ak_thread_exit();
}
static void *usbcam_video_stream_thread(void *arg)
{
while (m_uvc_dev.send_stream) {
if (m_uvc_dev.send_stream == USBCAM_STATE_STANDBY) {
ak_sleep_ms(200);
continue;
}
ak_thread_mutex_lock(&uvc_ctrl_mutex);
usbcam_video_stream_send();
ak_thread_mutex_unlock(&uvc_ctrl_mutex);
if (m_uvc_dev.ext_process) {
ak_sleep_ms(1000 / m_uvc_dev.out_fps);
} else {
ak_sleep_ms(5);
}
}
ak_thread_exit();
}
void py_usbcam_video_ext_process_config(void (*ext_process)(isp_frame_t *),
void (*ext_evt_cb)(int))
{
m_uvc_dev.ext_process = 1;
m_uvc_dev.ext_process_cb = ext_process;
m_uvc_dev.ext_event_cb = ext_evt_cb;
}
int py_video_camera_working()
{
if (m_uvc_dev.send_stream == USBCAM_STATE_WORKING) {
return 1;
}
return 0;
}
int py_usbcam_video_init(int camera_idx, int chan_idx)
{
int ret;
m_uvc_dev.camera_idx = camera_idx;
m_uvc_dev.uvc_fd = usbcam_video_open();
if (m_uvc_dev.uvc_fd < 0) {
LOG_E("usbcam_video_init sem create error\n");
m_uvc_dev.camera_idx = VIDEO_DEV0;
return -1;
}
m_uvc_dev.vi_chan = chan_idx;
INIT_LIST_HEAD(&uvc_cmd_list);
ret = ak_thread_sem_init(&uvc_ctrl_sem, 1);
if (ret < 0) {
close(m_uvc_dev.uvc_fd);
m_uvc_dev.uvc_fd = -1;
LOG_E("usbcam_video_init sem create error\n");
return -1;
}
ret = ak_thread_mutex_init(&uvc_ctrl_mutex, NULL);
if (ret < 0) {
close(m_uvc_dev.uvc_fd);
m_uvc_dev.uvc_fd = -1;
LOG_E("usbcam_video_init mutex create error\n");
return -1;
}
m_uvc_dev.monitor = 1;
if (ak_thread_create(&m_uvc_dev.monitor_thread, usbcam_video_monitor_thread,
NULL, ANYKA_THREAD_MIN_STACK_SIZE, 20) != 0) {
close(m_uvc_dev.uvc_fd);
m_uvc_dev.uvc_fd = -1;
m_uvc_dev.monitor = 0;
return -1;
}
m_uvc_dev.ctrl = 1;
if (ak_thread_create(&m_uvc_dev.ctrl_thread, usbcam_video_ctrl_thread, NULL,
ANYKA_THREAD_MIN_STACK_SIZE, 20) != 0) {
m_uvc_dev.monitor = 0;
ak_thread_join(m_uvc_dev.monitor_thread);
m_uvc_dev.monitor_thread = NULL;
close(m_uvc_dev.uvc_fd);
m_uvc_dev.uvc_fd = -1;
m_uvc_dev.ctrl = 0;
return -1;
}
m_uvc_dev.send_stream = USBCAM_STATE_STANDBY;
if (ak_thread_create(&m_uvc_dev.stream_thread, usbcam_video_stream_thread,
NULL, ANYKA_THREAD_MIN_STACK_SIZE, 20) != 0) {
m_uvc_dev.ctrl = 0;
ak_thread_sem_post(&uvc_ctrl_sem);
ak_thread_join(m_uvc_dev.ctrl_thread);
m_uvc_dev.ctrl_thread = NULL;
m_uvc_dev.monitor = 0;
ak_thread_join(m_uvc_dev.monitor_thread);
m_uvc_dev.monitor_thread = NULL;
close(m_uvc_dev.uvc_fd);
m_uvc_dev.uvc_fd = -1;
m_uvc_dev.send_stream = USBCAM_STATE_STOP;
return -1;
}
return 0;
}
int py_usbcam_video_deinit()
{
m_uvc_dev.send_stream = USBCAM_STATE_STOP;
if (m_uvc_dev.stream_thread != NULL) {
ak_thread_join(m_uvc_dev.stream_thread);
m_uvc_dev.stream_thread = NULL;
}
m_uvc_dev.send_stream = USBCAM_STATE_STANDBY;
py_usbcam_video_stream_stop();
m_uvc_dev.send_stream = USBCAM_STATE_STOP;
m_uvc_dev.ctrl = 0;
if (m_uvc_dev.ctrl_thread != NULL) {
ak_thread_sem_post(&uvc_ctrl_sem);
ak_thread_join(m_uvc_dev.ctrl_thread);
m_uvc_dev.ctrl_thread = NULL;
}
m_uvc_dev.monitor = 0;
if (m_uvc_dev.monitor_thread != NULL) {
ak_thread_join(m_uvc_dev.monitor_thread);
m_uvc_dev.monitor_thread = NULL;
}
if (m_uvc_dev.uvc_fd > 0) {
close(m_uvc_dev.uvc_fd);
m_uvc_dev.uvc_fd = -1;
}
ak_thread_mutex_destroy(&uvc_ctrl_mutex);
ak_thread_sem_destroy(&uvc_ctrl_sem);
m_uvc_dev.ext_process = 0;
m_uvc_dev.ext_event_cb = NULL;
m_uvc_dev.ext_process_cb = NULL;
return 0;
}
| YifuLiu/AliOS-Things | components/py_engine/modules/video/ak_usbcam.c | C | apache-2.0 | 12,219 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if MICROPY_PY_VIDEO
#include "py/builtin.h"
#include "py/obj.h"
#include "py/runtime.h"
extern const mp_obj_type_t video_player_type;
extern const mp_obj_type_t video_recorder_type;
extern const mp_obj_type_t video_camera_type;
STATIC const mp_rom_map_elem_t video_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_video) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Player), MP_ROM_PTR(&video_player_type) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_Recorder), MP_ROM_PTR(&video_recorder_type) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_camera), MP_ROM_PTR(&video_camera_type) },
};
STATIC MP_DEFINE_CONST_DICT(video_locals_dict, video_locals_dict_table);
const mp_obj_module_t video_module = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t *)&video_locals_dict,
};
MP_REGISTER_MODULE(MP_QSTR_video, video_module, MICROPY_PY_VIDEO);
#endif // MICROPY_PY_VIDEO | YifuLiu/AliOS-Things | components/py_engine/modules/video/modvideo.c | C | apache-2.0 | 948 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include "HaasLog.h"
#include "aos/kernel.h"
#include "k_api.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/runtime0.h"
#include "py/stream.h"
#include "timer.h"
#include "videocommon.h"
extern const mp_obj_type_t video_camera_type;
void video_camera_print(const mp_print_t *print, mp_obj_t self_in,
mp_print_kind_t kind)
{
mp_video_camera_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->mname);
}
static mp_obj_t video_camera_new(const mp_obj_type_t *type, size_t n_args,
size_t n_kw, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj = m_new_obj(mp_video_camera_obj_t);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_ENOMEM, "obj alloc fail");
camera_obj->base.type = &video_camera_type;
camera_obj->mname = "video-camera";
camera_obj->camera_idx = -1;
camera_obj->frame_rate = CAMERA_DEFAULT_FPS;
camera_obj->frame_release = 0;
camera_obj->frame = NULL;
return MP_OBJ_FROM_PTR(camera_obj);
}
static mp_obj_t video_camera_open(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
int camera_idx = 0;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 2, "args num is illegal");
if ((camera_idx = mp_obj_get_int(args[1])) < 0) {
LOG_E("%s: camera_idx(%d) is illegal\n", __func__, camera_idx);
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
if (camera_obj->frame == NULL) {
camera_obj->frame = m_new_obj(isp_frame_t);
if (camera_obj->frame) {
#if MICROPY_GC_CONSERVATIVE_CLEAR
memset(camera_obj->frame, 0, sizeof(isp_frame_t));
#endif
camera_obj->camera_idx = camera_idx;
camera_obj->frame_release = 0;
}
VIDEO_CAMERA_OBJ_INIT_CHK(camera_obj, MP_ENOMEM, "frame alloc failed");
py_video_camera_open(camera_obj->camera_idx, camera_obj->frame_rate);
}
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_camera_open_obj, 2, video_camera_open);
static mp_obj_t video_camera_close(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
if (camera_obj->frame) {
if (camera_obj->frame_release) {
py_video_camera_frame_release(camera_obj->frame);
}
camera_obj->frame_release = 0;
if (camera_obj->camera_idx >= 0) {
py_video_camera_close(camera_obj->camera_idx);
}
camera_obj->camera_idx = -1;
m_del_obj(isp_frame_t, camera_obj->frame);
camera_obj->frame = NULL;
m_del_obj(mp_video_camera_obj_t, camera_obj);
}
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_camera_close_obj, 1,
video_camera_close);
static mp_obj_t video_camera_preview(size_t n_args, const mp_obj_t *args)
{
uint32_t keep_time_second;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 2, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
keep_time_second = mp_obj_get_int(args[1]);
if (camera_obj->frame == NULL || camera_obj->camera_idx < 0) {
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
py_usbcam_video_init(VIDEO_DEV0, VIDEO_CHN0);
while (keep_time_second != 0) {
aos_msleep(1000);
keep_time_second--;
}
py_usbcam_video_deinit();
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_camera_preview_obj, 2,
video_camera_preview);
STATIC mp_obj_t video_camera_capture(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
if (camera_obj->frame != NULL && camera_obj->camera_idx >= 0) {
if (camera_obj->frame_release) {
py_video_camera_frame_release(camera_obj->frame);
}
if (py_video_camera_frame_get(camera_obj->frame) != 0) {
return MP_OBJ_FROM_PTR(NULL);
}
camera_obj->frame_release = 1;
}
return MP_OBJ_FROM_PTR(camera_obj->frame);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(video_camera_capture_obj, 1,
video_camera_capture);
STATIC mp_obj_t video_camera_save(size_t n_args, const mp_obj_t *args)
{
int pic_typ;
char *file_prefix;
isp_frame_t *frame;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 4, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
frame = (isp_frame_t *)MP_OBJ_TO_PTR(args[1]);
VIDEO_CAMERA_OBJ_CHK(frame, MP_EINVAL, "frame is NULL");
pic_typ = mp_obj_get_int(args[2]);
if (pic_typ != VIDEO_MEDIA_TYPE_YUV && pic_typ != VIDEO_MEDIA_TYPE_JPEG) {
LOG_E("%s, picture type not support\n", __func__);
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
file_prefix = (char *)mp_obj_str_get_str(args[3]);
VIDEO_CAMERA_OBJ_CHK(frame, MP_EINVAL, "save file_prefix is NULL");
// transfer raw frame to destination picture with type of pic_type;
// save destination picture to file of file_prefix;
py_video_camera_save(frame, pic_typ, (const char *)file_prefix);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(video_camera_save_obj, 4, video_camera_save);
STATIC mp_obj_t video_camera_config_set(size_t n_args, const mp_obj_t *args)
{
int prod_id;
void *prod_val;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 3, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
prod_id = mp_obj_get_int(args[1]);
prod_val = (void *)MP_OBJ_TO_PTR(args[2]);
// set config according to prod id and value;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(video_camera_config_set_obj, 3,
video_camera_config_set);
STATIC mp_obj_t video_camera_config_get(size_t n_args, const mp_obj_t *args)
{
int prod_id;
void *prod_val;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 3, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
prod_id = mp_obj_get_int(args[1]);
prod_val = (void *)MP_OBJ_TO_PTR(args[2]);
// get config according to prod id and save value to prod_val;
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR(video_camera_config_get_obj, 3,
video_camera_config_get);
STATIC const mp_rom_map_elem_t video_camera_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_camera) },
/* original YUV */
{ MP_OBJ_NEW_QSTR(MP_QSTR_YUV), MP_ROM_INT(VIDEO_MEDIA_TYPE_YUV) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_JPEG), MP_ROM_INT(VIDEO_MEDIA_TYPE_JPEG) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_H264), MP_ROM_INT(VIDEO_MEDIA_TYPE_H264) },
/* H265 or HEVC */
{ MP_OBJ_NEW_QSTR(MP_QSTR_HEVC), MP_ROM_INT(VIDEO_MEDIA_TYPE_HEVC) },
/* camera.save(frame, pic_type, path) */
{ MP_ROM_QSTR(MP_QSTR_save), MP_ROM_PTR(&video_camera_save_obj) },
/* camera.open(camara_idx) */
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&video_camera_open_obj) },
/* camera.close() */
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&video_camera_close_obj) },
/* camera.preview() */
{ MP_ROM_QSTR(MP_QSTR_preview), MP_ROM_PTR(&video_camera_preview_obj) },
/* frame = camera.capture() */
{ MP_ROM_QSTR(MP_QSTR_capture), MP_ROM_PTR(&video_camera_capture_obj) },
/* camera.set(proID, val) */
{ MP_ROM_QSTR(MP_QSTR_set), MP_ROM_PTR(&video_camera_config_set_obj) },
/* camera.get(proID, val) */
{ MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&video_camera_config_get_obj) },
};
STATIC MP_DEFINE_CONST_DICT(video_camera_globals, video_camera_globals_table);
const mp_obj_type_t video_camera_type = {
.base = { &mp_type_type },
.name = MP_QSTR_camera,
.print = video_camera_print,
.make_new = video_camera_new,
.locals_dict = (mp_obj_dict_t *)&video_camera_globals,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/video/videocamera.c | C | apache-2.0 | 8,964 |
#ifndef HAAS_VIDEO_COMMON_H
#define HAAS_VIDEO_COMMON_H
#include "ak_common.h"
#include "ak_vi.h"
#include "py/objlist.h"
#include "py/objstr.h"
#ifdef __cplusplus
extern "C" {
#endif
#define UVC_FILE "/dev/usbuvc"
#define UVC_DEFAULT_FORMAT VIDEO_MEDIA_TYPE_YUV
#define CAMERA_MAIN_CHN_DEFAULT_WIDTH (1920)
#define CAMERA_MAIN_CHN_DEFAULT_HEIGHT (1080)
#define CAMERA_SUB_CHN_DEFAULT_WIDTH (640)
#define CAMERA_SUB_CHN_DEFAULT_HEIGHT (320)
#define CAMERA_DEFAULT_FPS (20)
#define VIDEO_CAMERA_OBJ_CHK(obj, err_type, err_str) \
do { \
if (obj == NULL) { \
LOG_E("%s, %s\n", __func__, err_str); \
mp_raise_OSError(err_type); \
return mp_const_none; \
} \
} while (0)
#define VIDEO_CAMERA_RET_CHK(ret, dst_ret, err_str) \
do { \
if (obj != dst_ret) { \
LOG_E("%s, %s\n", __func__, err_str); \
mp_raise_OSError(MP_EIO); \
return mp_const_none; \
} \
} while (0)
#define VIDEO_CAMERA_OBJ_INIT_CHK(obj, err_type, err_str) \
do { \
if (obj == NULL || obj->frame == NULL) { \
LOG_E("%s, %s\n", __func__, err_str); \
mp_raise_OSError(err_type); \
return mp_const_none; \
} \
} while (0)
#define VIDEO_CAMERA_PARAM_CHK(n_arg, dst_cnt, err_str) \
do { \
if (n_arg != dst_cnt) { \
LOG_E("%s, %s, arg:%d\n", __func__, n_arg); \
mp_raise_OSError(MP_EINVAL); \
return mp_const_none; \
} \
} while (0)
enum {
VIDEO_MEDIA_TYPE_YUV = 0,
VIDEO_MEDIA_TYPE_JPEG,
VIDEO_MEDIA_TYPE_H264,
VIDEO_MEDIA_TYPE_HEVC,
};
typedef struct video_input_frame isp_frame_t;
typedef struct _camera_obj_t {
mp_obj_base_t base;
char *mname;
int camera_idx;
int frame_rate;
int frame_release;
isp_frame_t *frame;
} mp_video_camera_obj_t;
int py_video_camera_frame_get(isp_frame_t *frame);
int py_video_camera_frame_release(isp_frame_t *frame);
int py_video_camera_save(isp_frame_t *frame, int pic_type, const char *path);
int py_video_camera_open(int camera_idx, int frame_rate);
int py_video_camera_close(int camera_idx);
int py_video_camera_working();
int py_video_camera_config_set(int width, int height, int media_type);
int py_video_camera_config_get(int *width, int *height, int *media_type);
void py_usbcam_video_ext_process_config(void (*ext_process)(isp_frame_t *),
void (*ext_evt_cb)(int));
int py_venc_init(int width, int height, int fps, int media_type);
int py_usbcam_video_init(int camera_idx, int chan_idx);
int py_usbcam_video_deinit();
int py_rtsp_stop(void);
int py_rtsp_start(void);
int py_rtsp_close(void);
int py_rtsp_pause(void);
int py_rtsp_resume(void);
int py_rtsp_open(int camera_idx, int media_type, int fps, const char *url);
#ifdef __cplusplus
}
#endif
#endif
| YifuLiu/AliOS-Things | components/py_engine/modules/video/videocommon.h | C | apache-2.0 | 3,536 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "HaasLog.h"
#include "ak_common.h"
#include "ak_mem.h"
#include "ak_vi.h"
#include "k_api.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/runtime0.h"
#include "py/stream.h"
#include "videocommon.h"
extern const mp_obj_type_t video_player_type;
void video_player_print(const mp_print_t *print, mp_obj_t self_in,
mp_print_kind_t kind)
{
mp_video_camera_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->mname);
}
static mp_obj_t video_player_new(const mp_obj_type_t *type, size_t n_args,
size_t n_kw, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj = m_new_obj(mp_video_camera_obj_t);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_ENOMEM, "obj alloc fail");
camera_obj->base.type = &video_player_type;
camera_obj->mname = "video-player";
camera_obj->camera_idx = -1;
camera_obj->frame = NULL;
return MP_OBJ_FROM_PTR(camera_obj);
}
static mp_obj_t video_player_open(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
int camera_idx = 0;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 2, "args num is illegal");
if ((camera_idx = mp_obj_get_int(args[1])) < 0) {
LOG_E("%s: camera_idx(%d) is illegal\n", __func__, camera_idx);
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
if (camera_obj->frame == NULL) {
camera_obj->frame = m_new_obj(isp_frame_t);
if (camera_obj->frame) {
#if MICROPY_GC_CONSERVATIVE_CLEAR
memset(camera_obj->frame, 0, sizeof(isp_frame_t));
#endif
camera_obj->camera_idx = camera_idx;
}
}
VIDEO_CAMERA_OBJ_INIT_CHK(camera_obj, MP_ENOMEM, "frame alloc failed");
do {
sdk_run_config config;
memset(&config, 0, sizeof(config));
config.mem_trace_flag = SDK_RUN_NORMAL;
ak_sdk_init(&config);
} while (0);
if (ak_vi_open(camera_obj->camera_idx) != 0) {
LOG_E("ak_vi_open failed\n");
mp_raise_OSError(MP_ENOMEM);
return mp_const_none;
}
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_player_open_obj, 2, video_player_open);
static mp_obj_t video_player_close(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
if (camera_obj->frame) {
if (camera_obj->camera_idx >= 0)
ak_vi_close(camera_obj->camera_idx);
camera_obj->camera_idx = -1;
m_del_obj(isp_frame_t, camera_obj->frame);
camera_obj->frame = NULL;
}
m_del_obj(mp_video_camera_obj_t, camera_obj);
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_player_close_obj, 1,
video_player_close);
static mp_obj_t video_player_start(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_player_start_obj, 1,
video_player_start);
static mp_obj_t video_player_stop(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
return MP_OBJ_FROM_PTR(camera_obj->frame);
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_player_stop_obj, 1, video_player_stop);
static mp_obj_t video_player_save(size_t n_args, const mp_obj_t *args)
{
int pic_typ;
char *save_path;
isp_frame_t *frame;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 4, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
frame = (isp_frame_t *)MP_OBJ_TO_PTR(args[1]);
pic_typ = mp_obj_get_int(args[2]);
save_path = (char *)MP_OBJ_TO_PTR(args[3]);
// transfer raw frame to destination picture with type of pic_type;
// save destination picture to file of save_path;
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_player_save_obj, 4, video_player_save);
static mp_obj_t video_player_config_set(size_t n_args, const mp_obj_t *args)
{
int prod_id;
void *prod_val;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 3, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
prod_id = mp_obj_get_int(args[1]);
prod_val = (void *)MP_OBJ_TO_PTR(args[2]);
// set config according to prod id and value;
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_player_config_set_obj, 3,
video_player_config_set);
static mp_obj_t video_player_config_get(size_t n_args, const mp_obj_t *args)
{
int prod_id;
void *prod_val;
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 3, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
prod_id = mp_obj_get_int(args[1]);
prod_val = (void *)MP_OBJ_TO_PTR(args[2]);
// get config according to prod id and save value to prod_val;
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_player_config_get_obj, 3,
video_player_config_get);
static const mp_rom_map_elem_t video_player_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_Player) },
/* player.save(path) */
{ MP_ROM_QSTR(MP_QSTR_save), MP_ROM_PTR(&video_player_save_obj) },
/* player.open(camera_idx)
* player.open(url, media_type)
* player.open(path, media_type)
*/
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&video_player_open_obj) },
/* player.close() */
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&video_player_close_obj) },
/* player.start() */
{ MP_ROM_QSTR(MP_QSTR_start), MP_ROM_PTR(&video_player_start_obj) },
/* player.stop() */
{ MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&video_player_stop_obj) },
/* player.set(proID, val) */
{ MP_ROM_QSTR(MP_QSTR_set), MP_ROM_PTR(&video_player_config_set_obj) },
/* player.get(proID, val) */
{ MP_ROM_QSTR(MP_QSTR_get), MP_ROM_PTR(&video_player_config_get_obj) },
};
static MP_DEFINE_CONST_DICT(video_player_globals, video_player_globals_table);
const mp_obj_type_t video_player_type = {
.base = { &mp_type_type },
.name = MP_QSTR_Player,
.print = video_player_print,
.make_new = video_player_new,
.locals_dict = (mp_obj_dict_t *)&video_player_globals,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/video/videoplayer.c | C | apache-2.0 | 7,394 |
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "HaasLog.h"
#include "ak_common.h"
#include "ak_mem.h"
#include "ak_vi.h"
#include "k_api.h"
#include "py/mperrno.h"
#include "py/mphal.h"
#include "py/nlr.h"
#include "py/runtime.h"
#include "py/runtime0.h"
#include "py/stream.h"
#include "videocommon.h"
extern const mp_obj_type_t video_recorder_type;
void video_recorder_print(const mp_print_t *print, mp_obj_t self_in,
mp_print_kind_t kind)
{
mp_video_camera_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "modName(%s)", self->mname);
}
static mp_obj_t video_recorder_new(const mp_obj_type_t *type, size_t n_args,
size_t n_kw, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj = m_new_obj(mp_video_camera_obj_t);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_ENOMEM, "obj alloc fail");
camera_obj->base.type = &video_recorder_type;
camera_obj->mname = "video-recorder";
camera_obj->frame_rate = CAMERA_DEFAULT_FPS;
camera_obj->frame_release = 0;
camera_obj->camera_idx = -1;
camera_obj->frame = NULL;
return MP_OBJ_FROM_PTR(camera_obj);
}
static mp_obj_t video_recorder_open(size_t n_args, const mp_obj_t *args)
{
int ret = -1;
int camera_idx = 0;
mp_video_camera_obj_t *camera_obj;
int media_type = VIDEO_MEDIA_TYPE_H264;
if (n_args < 2 || n_args > 3) {
LOG_E("%s: n_args(%d) is illegal\n", __func__, n_args);
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
if ((camera_idx = mp_obj_get_int(args[1])) < 0) {
LOG_E("%s: camera_idx(%d) is illegal\n", __func__, camera_idx);
mp_raise_OSError(MP_EINVAL);
return mp_const_none;
}
if (n_args == 3) {
media_type = mp_obj_get_int(args[2]);
}
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
if (camera_obj->frame == NULL) {
camera_obj->frame = m_new_obj(isp_frame_t);
if (camera_obj->frame) {
#if MICROPY_GC_CONSERVATIVE_CLEAR
memset(camera_obj->frame, 0, sizeof(isp_frame_t));
#endif
camera_obj->camera_idx = camera_idx;
camera_obj->frame_release = 0;
}
VIDEO_CAMERA_OBJ_INIT_CHK(camera_obj, MP_ENOMEM, "frame alloc failed");
py_rtsp_open(camera_obj->camera_idx, media_type, camera_obj->frame_rate,
NULL);
}
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(video_recorder_open_obj, 2, 3,
video_recorder_open);
static mp_obj_t video_recorder_close(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
if (camera_obj->frame) {
if (camera_obj->camera_idx >= 0)
py_rtsp_close();
camera_obj->camera_idx = -1;
m_del_obj(isp_frame_t, camera_obj->frame);
camera_obj->frame = NULL;
}
m_del_obj(mp_video_camera_obj_t, camera_obj);
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_recorder_close_obj, 1,
video_recorder_close);
static mp_obj_t video_recorder_pause(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
py_rtsp_pause();
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_recorder_pause_obj, 1,
video_recorder_pause);
static mp_obj_t video_recorder_resume(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
py_rtsp_resume();
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_recorder_resume_obj, 1,
video_recorder_resume);
static mp_obj_t video_recorder_start(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
py_rtsp_start();
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_recorder_start_obj, 1,
video_recorder_start);
static mp_obj_t video_recorder_stop(size_t n_args, const mp_obj_t *args)
{
mp_video_camera_obj_t *camera_obj;
VIDEO_CAMERA_PARAM_CHK(n_args, 1, "args num is illegal");
camera_obj = (mp_video_camera_obj_t *)MP_OBJ_TO_PTR(args[0]);
VIDEO_CAMERA_OBJ_CHK(camera_obj, MP_EINVAL, "obj not init");
py_rtsp_stop();
return mp_const_none;
}
static MP_DEFINE_CONST_FUN_OBJ_VAR(video_recorder_stop_obj, 1,
video_recorder_stop);
static const mp_rom_map_elem_t video_recorder_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_Recorder) },
{ MP_OBJ_NEW_QSTR(MP_QSTR_H264), MP_ROM_INT(VIDEO_MEDIA_TYPE_H264) },
/* H265 or HEVC */
{ MP_OBJ_NEW_QSTR(MP_QSTR_HEVC), MP_ROM_INT(VIDEO_MEDIA_TYPE_HEVC) },
/* recorder.start() */
{ MP_ROM_QSTR(MP_QSTR_start), MP_ROM_PTR(&video_recorder_start_obj) },
/* recorder.stop() */
{ MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&video_recorder_stop_obj) },
/* recorder.open(camera_idx, media_type)
* recorder.open(url)
*/
{ MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&video_recorder_open_obj) },
/* recorder.close() */
{ MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&video_recorder_close_obj) },
/* recorder.pause() */
{ MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&video_recorder_pause_obj) },
/* recorder.resume() */
{ MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&video_recorder_resume_obj) },
};
static MP_DEFINE_CONST_DICT(video_recorder_globals,
video_recorder_globals_table);
const mp_obj_type_t video_recorder_type = {
.base = { &mp_type_type },
.name = MP_QSTR_Recorder,
.print = video_recorder_print,
.make_new = video_recorder_new,
.locals_dict = (mp_obj_dict_t *)&video_recorder_globals,
};
| YifuLiu/AliOS-Things | components/py_engine/modules/video/videorecorder.c | C | apache-2.0 | 6,654 |
# all tests need print to work! make sure it does work
print(1)
print('abc')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/0prelim.py | Python | apache-2.0 | 78 |
# test short circuit expressions outside if conditionals
print(() or 1)
print((1,) or 1)
print(() and 1)
print((1,) and 1)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/andor.py | Python | apache-2.0 | 123 |
# test PEP 526, varible annotations
x: int
print("x" in globals())
x: int = 1
print(x)
t: tuple = 1, 2
print(t)
# a pure annotation in a function makes that variable local
def f():
x: int
try:
print(x)
except NameError:
print("NameError")
f()
# here, "x" should remain a global
def f():
x.y: int
print(x)
f()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/annotate_var.py | Python | apache-2.0 | 350 |
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
a = array.array('B', [1, 2, 3])
print(a, len(a))
i = array.array('I', [1, 2, 3])
print(i, len(i))
print(a[0])
print(i[-1])
a = array.array('l', [-1])
print(len(a), a[0])
a1 = array.array('l', [1, 2, 3])
a2 = array.array('L', [1, 2, 3])
print(a2[1])
print(a1 == a2)
# Empty arrays
print(len(array.array('h')))
print(array.array('i'))
# bool operator acting on arrays
print(bool(array.array('i')))
print(bool(array.array('i', [1])))
# containment, with incorrect type
print('12' in array.array('B', b'12'))
print([] in array.array('B', b'12'))
# bad typecode
try:
array.array('X')
except ValueError:
print("ValueError")
# equality (CPython requires both sides are array)
print(bytes(array.array('b', [0x61, 0x62, 0x63])) == b'abc')
print(array.array('b', [0x61, 0x62, 0x63]) == b'abc')
print(array.array('B', [0x61, 0x62, 0x63]) == b'abc')
print(array.array('b', [0x61, 0x62, 0x63]) != b'abc')
print(array.array('b', [0x61, 0x62, 0x63]) == b'xyz')
print(array.array('b', [0x61, 0x62, 0x63]) != b'xyz')
print(b'abc' == array.array('b', [0x61, 0x62, 0x63]))
print(b'abc' == array.array('B', [0x61, 0x62, 0x63]))
print(b'abc' != array.array('b', [0x61, 0x62, 0x63]))
print(b'xyz' == array.array('b', [0x61, 0x62, 0x63]))
print(b'xyz' != array.array('b', [0x61, 0x62, 0x63]))
compatible_typecodes = []
for t in ["b", "h", "i", "l", "q"]:
compatible_typecodes.append((t, t))
compatible_typecodes.append((t, t.upper()))
for a, b in compatible_typecodes:
print(array.array(a, [1, 2]) == array.array(b, [1, 2]))
class X(array.array):
pass
print(bytes(X('b', [0x61, 0x62, 0x63])) == b'abc')
print(X('b', [0x61, 0x62, 0x63]) == b'abc')
print(X('b', [0x61, 0x62, 0x63]) != b'abc')
print(X('b', [0x61, 0x62, 0x63]) == array.array('b', [0x61, 0x62, 0x63]))
print(X('b', [0x61, 0x62, 0x63]) != array.array('b', [0x61, 0x62, 0x63]))
# other comparisons
for typecode in ["B", "H", "I", "L", "Q"]:
a = array.array(typecode, [1, 1])
print(a < a)
print(a <= a)
print(a > a)
print(a >= a)
al = array.array(typecode, [1, 0])
ab = array.array(typecode, [1, 2])
print(a < al)
print(a <= al)
print(a > al)
print(a >= al)
print(a < ab)
print(a <= ab)
print(a > ab)
print(a >= ab)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/array1.py | Python | apache-2.0 | 2,397 |
# test array + array
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
a1 = array.array('I', [1])
a2 = array.array('I', [2])
print(a1 + a2)
a1 += array.array('I', [3, 4])
print(a1)
a1.extend(array.array('I', [5]))
print(a1)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/array_add.py | Python | apache-2.0 | 330 |
# test construction of array.array from different objects
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
# tuple, list
print(array('b', (1, 2)))
print(array('h', [1, 2]))
# raw copy from bytes, bytearray
print(array('h', b'22')) # should be byteorder-neutral
print(array('h', bytearray(2)))
print(array('i', bytearray(4)))
# convert from other arrays
print(array('H', array('b', [1, 2])))
print(array('b', array('I', [1, 2])))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/array_construct.py | Python | apache-2.0 | 551 |
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
# construct from something with unknown length (requires generators)
print(array('i', (i for i in range(10))))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/array_construct2.py | Python | apache-2.0 | 278 |
# test construction of array.array from different objects
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
# raw copy from bytes, bytearray
print(array('h', b'12'))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/array_construct_endian.py | Python | apache-2.0 | 284 |
# test array types QqLl that require big-ints
try:
from uarray import array
except ImportError:
try:
from array import array
except ImportError:
print("SKIP")
raise SystemExit
print(array('L', [0, 2**32-1]))
print(array('l', [-2**31, 0, 2**31-1]))
print(array('q'))
print(array('Q'))
print(array('q', [0]))
print(array('Q', [0]))
print(array('q', [-2**63, -1, 0, 1, 2, 2**63-1]))
print(array('Q', [0, 1, 2, 2**64-1]))
print(bytes(array('q', [-1])))
print(bytes(array('Q', [2**64-1])))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/array_intbig.py | Python | apache-2.0 | 527 |
# test MicroPython-specific features of array.array
try:
import uarray as array
except ImportError:
try:
import array
except ImportError:
print("SKIP")
raise SystemExit
# arrays of objects
a = array.array('O')
a.append(1)
print(a[0])
# arrays of pointers
a = array.array('P')
a.append(1)
print(a[0])
# comparison between mismatching binary layouts is not implemented
typecodes = ["b", "h", "i", "l", "q", "P", "O", "S", "f", "d"]
for a in typecodes:
for b in typecodes:
if a == b and a not in ["f", "d"]:
continue
try:
array.array(a) == array.array(b)
print('FAIL')
except NotImplementedError:
pass
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/array_micropython.py | Python | apache-2.0 | 714 |
# test assignments
a = 1
print(a)
a = b = 2
print(a, b)
a = b = c = 3
print(a, b, c)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/assign1.py | Python | apache-2.0 | 89 |
(x := 4)
print(x)
if x := 2:
print(True)
print(x)
print(4, x := 5)
print(x)
x = 1
print(x, x := 5, x)
print(x)
def foo():
print("any", any((hit := i) % 5 == 3 and (hit % 2) == 0 for i in range(10)))
return hit
hit = 123
print(foo())
print(hit) # shouldn't be changed by foo
print("any", any((hit := i) % 5 == 3 and (hit % 2) == 0 for i in range(10)))
print(hit) # should be changed by above
print([((m := k + 1), k * m) for k in range(4)])
print(m)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/assign_expr.py | Python | apache-2.0 | 472 |
# test SyntaxError with := operator
def test(code):
try:
print(eval(code))
except SyntaxError:
print('SyntaxError')
test("x := 1")
test("((x, y) := 1)")
# these are currently all allowed in MicroPython, but not in CPython
test("([i := i + 1 for i in range(4)])")
test("([i := -1 for i, j in [(1, 2)]])")
test("([[(i := j) for i in range(2)] for j in range(2)])")
test("([[(j := i) for i in range(2)] for j in range(2)])")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/assign_expr_syntaxerror.py | Python | apache-2.0 | 449 |
# test basic await expression
# adapted from PEP0492
async def abinary(n):
print(n)
if n <= 0:
return 1
l = await abinary(n - 1)
r = await abinary(n - 1)
return l + 1 + r
o = abinary(4)
try:
while True:
o.send(None)
except StopIteration:
print('finished')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_await.py | Python | apache-2.0 | 302 |
# test await expression
try:
import usys as sys
except ImportError:
import sys
if sys.implementation.name == 'micropython':
# uPy allows normal generators to be awaitables
coroutine = lambda f: f
else:
import types
coroutine = types.coroutine
@coroutine
def wait(value):
print('wait value:', value)
msg = yield 'message from wait({})'.format(value)
print('wait got back:', msg)
return 10
async def f():
x = await wait(1)**2
print('x =', x)
coro = f()
print('return from send:', coro.send(None))
try:
coro.send('message from main')
except StopIteration:
print('got StopIteration')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_await2.py | Python | apache-2.0 | 640 |
# test async def
def dec(f):
print('decorator')
return f
# test definition with a decorator
@dec
async def foo():
print('foo')
coro = foo()
try:
coro.send(None)
except StopIteration:
print('StopIteration')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_def.py | Python | apache-2.0 | 229 |
# test basic async for execution
# example taken from PEP0492
class AsyncIteratorWrapper:
def __init__(self, obj):
print('init')
self._it = iter(obj)
def __aiter__(self):
print('aiter')
return self
async def __anext__(self):
print('anext')
try:
value = next(self._it)
except StopIteration:
raise StopAsyncIteration
return value
async def coro():
async for letter in AsyncIteratorWrapper('abc'):
print(letter)
o = coro()
try:
o.send(None)
except StopIteration:
print('finished')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_for.py | Python | apache-2.0 | 603 |
# test waiting within "async for" __anext__ function
try:
import usys as sys
except ImportError:
import sys
if sys.implementation.name == 'micropython':
# uPy allows normal generators to be awaitables
coroutine = lambda f: f
else:
import types
coroutine = types.coroutine
@coroutine
def f(x):
print('f start:', x)
yield x + 1
yield x + 2
return x + 3
class ARange:
def __init__(self, high):
print('init')
self.cur = 0
self.high = high
def __aiter__(self):
print('aiter')
return self
async def __anext__(self):
print('anext')
print('f returned:', await f(20))
if self.cur < self.high:
val = self.cur
self.cur += 1
return val
else:
raise StopAsyncIteration
async def coro():
async for x in ARange(4):
print('x', x)
o = coro()
try:
while True:
print('coro yielded:', o.send(None))
except StopIteration:
print('finished')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_for2.py | Python | apache-2.0 | 1,025 |
# test syntax errors using async
try:
exec
except NameError:
print("SKIP")
raise SystemExit
def test_syntax(code):
try:
exec(code)
print("no SyntaxError")
except SyntaxError:
print("SyntaxError")
test_syntax("async for x in (): x")
test_syntax("async with x: x")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_syntaxerror.py | Python | apache-2.0 | 312 |
# test simple async with execution
class AContext:
async def __aenter__(self):
print('enter')
return 1
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc)
async def f():
async with AContext():
print('body')
o = f()
try:
o.send(None)
except StopIteration:
print('finished')
async def g():
async with AContext() as ac:
print(ac)
raise ValueError('error')
o = g()
try:
o.send(None)
except ValueError:
print('ValueError')
# test raising BaseException to make sure it is handled by the async-with
async def h():
async with AContext():
raise BaseException
o = h()
try:
o.send(None)
except BaseException:
print('BaseException')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_with.py | Python | apache-2.0 | 750 |
# test waiting within async with enter/exit functions
try:
import usys as sys
except ImportError:
import sys
if sys.implementation.name == 'micropython':
# uPy allows normal generators to be awaitables
coroutine = lambda f: f
else:
import types
coroutine = types.coroutine
@coroutine
def f(x):
print('f start:', x)
yield x + 1
yield x + 2
return x + 3
class AContext:
async def __aenter__(self):
print('enter')
print('f returned:', await f(10))
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc)
print('f returned:', await f(20))
async def coro():
async with AContext():
print('body start')
print('body f returned:', await f(30))
print('body end')
o = coro()
try:
while True:
print('coro yielded:', o.send(None))
except StopIteration:
print('finished')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_with2.py | Python | apache-2.0 | 906 |
# test async with, escaped by a break
class AContext:
async def __aenter__(self):
print('enter')
return 1
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc)
async def f1():
while 1:
async with AContext():
print('body')
break
print('no 1')
print('no 2')
o = f1()
try:
print(o.send(None))
except StopIteration:
print('finished')
async def f2():
while 1:
try:
async with AContext():
print('body')
break
print('no 1')
finally:
print('finally')
print('no 2')
o = f2()
try:
print(o.send(None))
except StopIteration:
print('finished')
async def f3():
while 1:
try:
try:
async with AContext():
print('body')
break
print('no 1')
finally:
print('finally inner')
finally:
print('finally outer')
print('no 2')
o = f3()
try:
print(o.send(None))
except StopIteration:
print('finished')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_with_break.py | Python | apache-2.0 | 1,171 |
# test async with, escaped by a return
class AContext:
async def __aenter__(self):
print('enter')
return 1
async def __aexit__(self, exc_type, exc, tb):
print('exit', exc_type, exc)
async def f1():
async with AContext():
print('body')
return
o = f1()
try:
o.send(None)
except StopIteration:
print('finished')
async def f2():
try:
async with AContext():
print('body')
return
finally:
print('finally')
o = f2()
try:
o.send(None)
except StopIteration:
print('finished')
async def f3():
try:
try:
async with AContext():
print('body')
return
finally:
print('finally inner')
finally:
print('finally outer')
o = f3()
try:
o.send(None)
except StopIteration:
print('finished')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/async_with_return.py | Python | apache-2.0 | 887 |
# test attrtuple
# we can't test this type directly so we use sys.implementation object
try:
import usys as sys
except ImportError:
import sys
t = sys.implementation
# It can be just a normal tuple on small ports
try:
t.name
except AttributeError:
print("SKIP")
raise SystemExit
# test printing of attrtuple
print(str(t).find("version=") > 0)
# test read attr
print(isinstance(t.name, str))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/attrtuple1.py | Python | apache-2.0 | 416 |
# tests for bool objects
# basic logic
print(not False)
print(not True)
print(False and True)
print(False or True)
# unary operators
print(+True)
print(-True)
# comparison with itself
print(False == False)
print(False == True)
print(True == False)
print(True == True)
print(False != False)
print(False != True)
print(True != False)
print(True != True)
# comparison with integers
print(False == 0)
print(0 == False)
print(True == 1)
print(1 == True)
print(True == 2)
print(2 == True)
print(False != 0)
print(0 != False)
print(True != 1)
print(1 != True)
print(True != 2)
print(2 != True)
# unsupported unary op
try:
len(False)
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/bool1.py | Python | apache-2.0 | 676 |
# tests basics of bound methods
# uPy and CPython differ when printing a bound method, so just print the type
print(type(repr([].append)))
class A:
def f(self):
return 0
def g(self, a):
return a
def h(self, a, b, c, d, e, f):
return a + b + c + d + e + f
# bound method with no extra args
m = A().f
print(m())
# bound method with 1 extra arg
m = A().g
print(m(1))
# bound method with lots of extra args
m = A().h
print(m(1, 2, 3, 4, 5, 6))
# can't assign attributes to a bound method
try:
A().f.x = 1
except AttributeError:
print('AttributeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/boundmeth1.py | Python | apache-2.0 | 598 |
while True:
break
for i in range(4):
print('one', i)
if i > 2:
break
print('two', i)
for i in [1, 2, 3, 4]:
if i == 3:
break
print(i)
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/break.py | Python | apache-2.0 | 176 |
# test builtin abs
print(abs(False))
print(abs(True))
print(abs(1))
print(abs(-1))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_abs.py | Python | apache-2.0 | 84 |
# test builtin abs
# bignum
print(abs(123456789012345678901234567890))
print(abs(-123456789012345678901234567890))
# edge cases for 32 and 64 bit archs (small int overflow when negating)
print(abs(-0x3fffffff - 1))
print(abs(-0x3fffffffffffffff - 1))
# edge case for nan-boxing with 47-bit small int
i = -0x3fffffffffff
print(abs(i - 1))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_abs_intbig.py | Python | apache-2.0 | 341 |
# test builtin "all" and "any"
tests = (
(),
[],
[False],
[True],
[False, True],
[True, False],
[False, False],
[True, True],
range(10),
)
for test in tests:
print(all(test))
for test in tests:
print(any(test))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_allany.py | Python | apache-2.0 | 258 |
# test builtin bin function
print(bin(1))
print(bin(-1))
print(bin(15))
print(bin(-15))
print(bin(12345))
print(bin(0b10101))
print(bin(0b10101010101010101010))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_bin.py | Python | apache-2.0 | 164 |
# test builtin bin function
print(bin(12345678901234567890))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_bin_intbig.py | Python | apache-2.0 | 62 |
# test builtin callable
# primitives should not be callable
print(callable(None))
print(callable(1))
print(callable([]))
print(callable("dfsd"))
# modules should not be callabe
try:
import usys as sys
except ImportError:
import sys
print(callable(sys))
# builtins should be callable
print(callable(callable))
# lambdas should be callable
print(callable(lambda:None))
# user defined functions should be callable
def f():
pass
print(callable(f))
# types should be callable, but not instances
class A:
pass
print(callable(A))
print(callable(A()))
# instances with __call__ method should be callable
class B:
def __call__(self):
pass
print(callable(B()))
# this checks internal use of callable when extracting members from an instance
class C:
def f(self):
return "A.f"
class D:
g = C() # g is a value and is not callable
print(callable(D().g))
print(D().g.f())
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_callable.py | Python | apache-2.0 | 910 |
# test builtin chr (whether or not we support unicode)
print(chr(65))
try:
chr(0x110000)
except ValueError:
print("ValueError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_chr.py | Python | apache-2.0 | 139 |
# test compile builtin
try:
compile
except NameError:
print("SKIP")
raise SystemExit
def test():
global x
c = compile("print(x)", "file", "exec")
try:
exec(c)
except NameError:
print("NameError")
# global variable for compiled code to access
x = 1
exec(c)
exec(c, {"x":2})
exec(c, {}, {"x":3})
# single/eval mode
exec(compile("if 1: 10 + 1\n", "file", "single"))
exec(compile("print(10 + 2)", "file", "single"))
print(eval(compile("10 + 3", "file", "eval")))
# bad mode
try:
compile('1', 'file', '')
except ValueError:
print("ValueError")
# exception within compiled code
try:
exec(compile('noexist', 'file', 'exec'))
except NameError:
print("NameError")
print(x) # check 'x' still exists as a global
test()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_compile.py | Python | apache-2.0 | 859 |
# test builtin delattr
try:
delattr
except:
print("SKIP")
raise SystemExit
class A: pass
a = A()
a.x = 1
print(a.x)
delattr(a, 'x')
try:
a.x
except AttributeError:
print('AttributeError')
try:
delattr(a, 'x')
except AttributeError:
print('AttributeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_delattr.py | Python | apache-2.0 | 288 |
# test builtin dir
# dir of locals
print('__name__' in dir())
# dir of module
try:
import usys as sys
except ImportError:
import sys
print('version' in dir(sys))
# dir of type
print('append' in dir(list))
class Foo:
def __init__(self):
self.x = 1
foo = Foo()
print('__init__' in dir(foo))
print('x' in dir(foo))
# dir of subclass
class A:
def a():
pass
class B(A):
def b():
pass
d = dir(B())
print(d.count('a'), d.count('b'))
# dir of class with multiple bases and a common parent
class C(A):
def c():
pass
class D(B, C):
def d():
pass
d = dir(D())
print(d.count('a'), d.count('b'), d.count('c'), d.count('d'))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_dir.py | Python | apache-2.0 | 685 |
# test builtin divmod
print(divmod(0, 2))
print(divmod(3, 4))
print(divmod(20, 3))
try:
divmod(1, 0)
except ZeroDivisionError:
print("ZeroDivisionError")
try:
divmod('a', 'b')
except TypeError:
print("TypeError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_divmod.py | Python | apache-2.0 | 232 |
# test builtin divmod
try:
divmod(1 << 65, 0)
except ZeroDivisionError:
print("ZeroDivisionError")
# bignum
l = (1 << 65) + 123
print(divmod(3, l))
print(divmod(l, 5))
print(divmod(l + 3, l))
print(divmod(l * 20, l + 2))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_divmod_intbig.py | Python | apache-2.0 | 231 |
# tests that .../Ellipsis exists
print(...)
print(Ellipsis)
print(... == Ellipsis)
# Test that Ellipsis can be hashed
print(type(hash(Ellipsis)))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_ellipsis.py | Python | apache-2.0 | 149 |
try:
enumerate
except:
print("SKIP")
raise SystemExit
print(list(enumerate([])))
print(list(enumerate([1, 2, 3])))
print(list(enumerate([1, 2, 3], 5)))
print(list(enumerate([1, 2, 3], -5)))
print(list(enumerate(range(100))))
# specifying args with keywords
print(list(enumerate([1, 2, 3], start=1)))
print(list(enumerate(iterable=[1, 2, 3])))
print(list(enumerate(iterable=[1, 2, 3], start=1)))
# check handling of extra positional args (exercises some logic in mp_arg_parse_all)
# don't print anything because it doesn't error with MICROPY_CPYTHON_COMPAT disabled
try:
enumerate([], 1, 2)
except TypeError:
pass
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_enumerate.py | Python | apache-2.0 | 636 |
# builtin eval
try:
eval
except NameError:
print("SKIP")
raise SystemExit
eval('1 + 2')
eval('1 + 2\n')
eval('1 + 2\n\n#comment\n')
x = 4
eval('x')
eval('lambda x: x + 10')(-5)
y = 6
eval('lambda: y * 2')()
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_eval.py | Python | apache-2.0 | 224 |
# test builtin eval with a buffer (bytearray/memoryview) input
try:
eval
bytearray
memoryview
except:
print("SKIP")
raise SystemExit
print(eval(bytearray(b'1 + 1')))
print(eval(memoryview(b'2 + 2')))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_eval_buffer.py | Python | apache-2.0 | 222 |
# test if eval raises SyntaxError
try:
eval
except NameError:
print("SKIP")
raise SystemExit
try:
print(eval("[1,,]"))
except SyntaxError:
print("SyntaxError")
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_eval_error.py | Python | apache-2.0 | 182 |
# test builtin exec
try:
exec
except NameError:
print("SKIP")
raise SystemExit
print(exec("def foo(): return 42"))
print(foo())
d = {}
exec("def bar(): return 84", d)
print(d["bar"]())
# passing None/dict as args to globals/locals
foo = 11
exec('print(foo)')
exec('print(foo)', None)
exec('print(foo)', {'foo':3}, None)
exec('print(foo)', None, {'foo':3})
exec('print(foo)', None, {'bar':3})
exec('print(foo)', {'bar':3}, locals())
try:
exec('print(foo)', {'bar':3}, None)
except NameError:
print('NameError')
# invalid arg passed to globals
try:
exec('print(1)', 'foo')
except TypeError:
print('TypeError')
# invalid arg passed to locals
try:
exec('print(1)', None, 123)
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_exec.py | Python | apache-2.0 | 752 |
# test builtin exec with a buffer (bytearray/memoryview) input
try:
exec
bytearray
memoryview
except:
print("SKIP")
raise SystemExit
exec(bytearray(b'print(1)'))
exec(memoryview(b'print(2)'))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_exec_buffer.py | Python | apache-2.0 | 214 |
try:
filter
except:
print("SKIP")
raise SystemExit
print(list(filter(lambda x: x & 1, range(-3, 4))))
print(list(filter(None, range(-3, 4))))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_filter.py | Python | apache-2.0 | 155 |
class A:
var = 132
def __init__(self):
self.var2 = 34
def meth(self, i):
return 42 + i
a = A()
print(getattr(a, "var"))
print(getattr(a, "var2"))
print(getattr(a, "meth")(5))
print(getattr(a, "_none_such", 123))
print(getattr(list, "foo", 456))
print(getattr(a, "va" + "r2"))
# test a class that defines __getattr__ and may raise AttributeError
class B:
def __getattr__(self, attr):
if attr == "a":
return attr
else:
raise AttributeError
b = B()
print(getattr(b, "a"))
print(getattr(b, "a", "default"))
print(getattr(b, "b", "default"))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_getattr.py | Python | apache-2.0 | 615 |
class A:
var = 132
def __init__(self):
self.var2 = 34
def meth(self, i):
return 42 + i
a = A()
print(hasattr(a, "var"))
print(hasattr(a, "var2"))
print(hasattr(a, "meth"))
print(hasattr(a, "_none_such"))
print(hasattr(list, "foo"))
class C:
def __getattr__(self, attr):
if attr == "exists":
return attr
elif attr == "raise":
raise Exception(123)
raise AttributeError
c = C()
print(hasattr(c, "exists"))
print(hasattr(c, "doesnt_exist"))
# ensure that non-AttributeError exceptions propagate out of hasattr
try:
hasattr(c, "raise")
except Exception as er:
print(er)
try:
hasattr(1, b'123')
except TypeError:
print('TypeError')
try:
hasattr(1, 123)
except TypeError:
print('TypeError')
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_hasattr.py | Python | apache-2.0 | 799 |
# test builtin hash function
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({(1,):1}) # hash non-empty tuple
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return "a instance"
print(hash(A()))
print({A():1})
# all user-classes have default __hash__
class B:
pass
hash(B())
# if __eq__ is defined then default __hash__ is not used
class C:
def __eq__(self, another):
return True
try:
hash(C())
except TypeError:
print("TypeError")
# __hash__ must return an int
class D:
def __hash__(self):
return None
try:
hash(D())
except TypeError:
print("TypeError")
# __hash__ returning a bool should be converted to an int
class E:
def __hash__(self):
return True
print(hash(E()))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_hash.py | Python | apache-2.0 | 892 |
# test builtin hash function, on generators
def gen():
yield
print(type(hash(gen)))
print(type(hash(gen())))
| YifuLiu/AliOS-Things | components/py_engine/tests/basics/builtin_hash_gen.py | Python | apache-2.0 | 115 |