chore: Remove tracked build artifacts

This commit is contained in:
lmx
2025-11-28 16:24:27 +08:00
parent 892ed9267b
commit 818e8c3778
2356 changed files with 0 additions and 587882 deletions

View File

@ -1,422 +0,0 @@
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_main.h"
#include "tuya_ble_secure.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_sdk_version.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_event.h"
#include "tuya_ble_app_demo.h"
//#include "tuya_ble_demo_version.h"
#include "tuya_ble_log.h"
#include "tuya_ota.h"
#include "system/generic/printf.h"
#include "log.h"
#include "system/includes.h"
//#include "ota.h"
tuya_ble_device_param_t device_param = {0};
#define LED_PIN IO_PORTA_01
static bool tuya_led_state = 0;
//烧写器烧写三元组时这里置零
#define TUYA_INFO_TEST 0
#if TUYA_INFO_TEST
static const char device_id_test[] = "tuya58253f7c8ed1";
static const char auth_key_test[] = "I9ikbTKVMhfvEDgARBCtFbAWUpZIRdyv";
static const uint8_t mac_test[6] = {0xDC, 0x23, 0x4D, 0x65, 0xB0, 0x66}; //The actual MAC address is : 66:55:44:33:22:11
#endif /* TUYA_INFO_TEST */
#define APP_CUSTOM_EVENT_1 1
#define APP_CUSTOM_EVENT_2 2
#define APP_CUSTOM_EVENT_3 3
#define APP_CUSTOM_EVENT_4 4
#define APP_CUSTOM_EVENT_5 5
static uint8_t dp_data_array[255 + 3];
static uint16_t dp_data_len = 0;
typedef struct {
uint8_t data[50];
} custom_data_type_t;
void custom_data_process(int32_t evt_id, void *data)
{
custom_data_type_t *event_1_data;
TUYA_APP_LOG_DEBUG("custom event id = %d", evt_id);
switch (evt_id) {
case APP_CUSTOM_EVENT_1:
event_1_data = (custom_data_type_t *)data;
TUYA_APP_LOG_HEXDUMP_DEBUG("received APP_CUSTOM_EVENT_1 data:", event_1_data->data, 50);
break;
case APP_CUSTOM_EVENT_2:
break;
case APP_CUSTOM_EVENT_3:
break;
case APP_CUSTOM_EVENT_4:
break;
case APP_CUSTOM_EVENT_5:
break;
default:
break;
}
}
custom_data_type_t custom_data;
void custom_evt_1_send_test(uint8_t data)
{
tuya_ble_custom_evt_t event;
for (uint8_t i = 0; i < 50; i++) {
custom_data.data[i] = data;
}
event.evt_id = APP_CUSTOM_EVENT_1;
event.custom_event_handler = (void *)custom_data_process;
event.data = &custom_data;
tuya_ble_custom_event_send(event);
}
static uint16_t sn = 0;
static uint32_t time_stamp = 1587795793;
void tuya_data_init()
{
struct {
uint8_t id;
uint8_t type;
uint16_t len;
uint8_t data;
} p_dp_data;
p_dp_data.id = 1;
p_dp_data.type = 1;
p_dp_data.len = 0x0100;
p_dp_data.data = tuya_led_state;
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x03)
tuya_ble_dp_data_report(&p_dp_data, 5); //1
#endif
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x04)
tuya_ble_dp_data_send(sn, DP_SEND_TYPE_ACTIVE, DP_SEND_FOR_CLOUD_PANEL, DP_SEND_WITH_RESPONSE, &p_dp_data, 5);
#endif
}
void tuya_data_parse(tuya_ble_cb_evt_param_t *event)
{
uint8_t *buf = event->dp_received_data.p_data;
uint32_t sn = event->dp_received_data.sn;
put_buf(buf, event->dp_received_data.data_len);
struct {
uint8_t id;
uint8_t type;
uint16_t len;
uint8_t data;
} p_dp_data;
p_dp_data.id = buf[0];
p_dp_data.type = buf[1];
p_dp_data.len = 0x0100;
p_dp_data.data = buf[4];
printf("\n\n<-------------- tuya_data_parse -------------->");
printf("sn = %d, id = %d, type = %d, len = %d, data = %d", sn, p_dp_data.id, p_dp_data.type, p_dp_data.len, p_dp_data.data);
switch (buf[0]) {
case 1:
printf("tuya switch control, onoff set to: %d\n", p_dp_data.data);
tuya_led_state = p_dp_data.data;
gpio_direction_output(LED_PIN, tuya_led_state);
break;
//case 2:
//printf("tuya mode control, mode set to: %d\n", buf[3]);
//break;
default:
printf("unknow control msg len = %d, data:", buf[2]);
break;
}
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x03)
tuya_ble_dp_data_report(&p_dp_data, 5); //1
#endif
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x04)
tuya_ble_dp_data_send(sn, DP_SEND_TYPE_ACTIVE, DP_SEND_FOR_CLOUD_PANEL, DP_SEND_WITH_RESPONSE, &p_dp_data, 5);
#endif
}
static void tuya_cb_handler(tuya_ble_cb_evt_param_t *event)
{
int16_t result = 0;
printf("tuya cb_handler event->evt=0x%x\n", event->evt);
switch (event->evt) {
case TUYA_BLE_CB_EVT_CONNECTE_STATUS:
TUYA_APP_LOG_INFO("received tuya ble conncet status update event,current connect status = %d", event->connect_status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_RECEIVED:
tuya_data_parse(event);
break;
case TUYA_BLE_CB_EVT_DP_DATA_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data report response result code =%d", event->dp_response_data.status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_WTTH_TIME_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data report response result code =%d", event->dp_response_data.status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_WITH_FLAG_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data with flag report response sn = %d , flag = %d , result code =%d", event->dp_with_flag_response_data.sn, event->dp_with_flag_response_data.mode
, event->dp_with_flag_response_data.status);
break;
case TUYA_BLE_CB_EVT_DP_DATA_WITH_FLAG_AND_TIME_REPORT_RESPONSE:
TUYA_APP_LOG_INFO("received dp data with flag and time report response sn = %d , flag = %d , result code =%d", event->dp_with_flag_and_time_response_data.sn,
event->dp_with_flag_and_time_response_data.mode, event->dp_with_flag_and_time_response_data.status);
break;
case TUYA_BLE_CB_EVT_UNBOUND:
TUYA_APP_LOG_INFO("received unbound req");
break;
case TUYA_BLE_CB_EVT_ANOMALY_UNBOUND:
TUYA_APP_LOG_INFO("received anomaly unbound req");
break;
case TUYA_BLE_CB_EVT_DEVICE_RESET:
TUYA_APP_LOG_INFO("received device reset req");
break;
case TUYA_BLE_CB_EVT_DP_QUERY:
TUYA_APP_LOG_INFO("received TUYA_BLE_CB_EVT_DP_QUERY event");
if (dp_data_len > 0) {
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x03)
tuya_ble_dp_data_report(dp_data_array, dp_data_len);
#endif
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN == 0x04)
tuya_ble_dp_data_send(sn, DP_SEND_TYPE_ACTIVE, DP_SEND_FOR_CLOUD_PANEL, DP_SEND_WITH_RESPONSE, dp_data_array, dp_data_len);
#endif
}
break;
case TUYA_BLE_CB_EVT_OTA_DATA:
tuya_ota_proc(event->ota_data.type, event->ota_data.p_data, event->ota_data.data_len);
break;
case TUYA_BLE_CB_EVT_NETWORK_INFO:
TUYA_APP_LOG_INFO("received net info : %s", event->network_data.p_data);
tuya_ble_net_config_response(result);
break;
case TUYA_BLE_CB_EVT_WIFI_SSID:
break;
case TUYA_BLE_CB_EVT_TIME_STAMP:
TUYA_APP_LOG_INFO("received unix timestamp : %s ,time_zone : %d", event->timestamp_data.timestamp_string, event->timestamp_data.time_zone);
tuya_data_init();
break;
case TUYA_BLE_CB_EVT_TIME_NORMAL:
break;
case TUYA_BLE_CB_EVT_DATA_PASSTHROUGH:
TUYA_APP_LOG_HEXDUMP_DEBUG("received ble passthrough data :", event->ble_passthrough_data.p_data, event->ble_passthrough_data.data_len);
tuya_ble_data_passthrough(event->ble_passthrough_data.p_data, event->ble_passthrough_data.data_len);
break;
default:
TUYA_APP_LOG_WARNING("app_tuya_cb_queue msg: unknown event type 0x%04x", event->evt);
break;
}
tuya_ble_inter_event_response(event);
}
#define TUYA_LEGAL_CHAR(c) ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
static u16 tuya_get_one_info(const u8 *in, u8 *out)
{
int read_len = 0;
const u8 *p = in;
while (TUYA_LEGAL_CHAR(*p) && *p != ',') { //read product_uuid
*out++ = *p++;
read_len++;
}
return read_len;
}
typedef struct __flash_of_lic_para_head {
s16 crc;
u16 string_len;
const u8 para_string[];
} __attribute__((packed)) _flash_of_lic_para_head;
#define LIC_PAGE_OFFSET 80
static bool license_para_head_check(u8 *para)
{
_flash_of_lic_para_head *head;
//fill head
head = (_flash_of_lic_para_head *)para;
///crc check
u8 *crc_data = (u8 *)(para + sizeof(((_flash_of_lic_para_head *)0)->crc));
u32 crc_len = sizeof(_flash_of_lic_para_head) - sizeof(((_flash_of_lic_para_head *)0)->crc)/*head crc*/ + (head->string_len)/*content crc,include end character '\0'*/;
s16 crc_sum = 0;
crc_sum = CRC16(crc_data, crc_len);
if (crc_sum != head->crc) {
printf("license crc error !!! %x %x \n", (u32)crc_sum, (u32)head->crc);
return false;
}
return true;
}
const u8 *tuya_get_license_ptr(void)
{
u32 flash_capacity = sdfile_get_disk_capacity();
u32 flash_addr = flash_capacity - 256 + LIC_PAGE_OFFSET;
u8 *lic_ptr = NULL;
_flash_of_lic_para_head *head;
printf("flash capacity:%x \n", flash_capacity);
lic_ptr = (u8 *)sdfile_flash_addr2cpu_addr(flash_addr);
//head length check
head = (_flash_of_lic_para_head *)lic_ptr;
if (head->string_len >= 0xff) {
printf("license length error !!! \n");
return NULL;
}
////crc check
if (license_para_head_check(lic_ptr) == (false)) {
printf("license head check fail\n");
return NULL;
}
//put_buf(lic_ptr, 128);
lic_ptr += sizeof(_flash_of_lic_para_head);
return lic_ptr;
}
static uint8_t read_tuya_product_info_from_flash(uint8_t *read_buf, u16 buflen)
{
uint8_t *rp = read_buf;
const uint8_t *tuya_ptr = (uint8_t *)tuya_get_license_ptr();
//printf("tuya_ptr:");
//put_buf(tuya_ptr, 69);
if (tuya_ptr == NULL) {
return FALSE;
}
int data_len = 0;
data_len = tuya_get_one_info(tuya_ptr, rp);
//put_buf(rp, data_len);
if (data_len != 16) {
printf("read uuid err, data_len:%d", data_len);
put_buf(rp, data_len);
return FALSE;
}
tuya_ptr += 17;
rp = read_buf + 16;
data_len = tuya_get_one_info(tuya_ptr, rp);
//put_buf(rp, data_len);
if (data_len != 32) {
printf("read key err, data_len:%d", data_len);
put_buf(rp, data_len);
return FALSE;
}
tuya_ptr += 33;
rp = read_buf + 16 + 32;
data_len = tuya_get_one_info(tuya_ptr, rp);
//put_buf(rp, data_len);
if (data_len != 12) {
printf("read mac err, data_len:%d", data_len);
put_buf(rp, data_len);
return FALSE;
}
return TRUE;
}
static u8 ascii_to_hex(u8 in)
{
if (in >= '0' && in <= '9') {
return in - '0';
} else if (in >= 'a' && in <= 'f') {
return in - 'a' + 0x0a;
} else if (in >= 'A' && in <= 'F') {
return in - 'A' + 0x0a;
} else {
printf("tuya ascii to hex error, data:0x%x", in);
return 0;
}
}
static void parse_mac_data(u8 *in, u8 *out)
{
for (int i = 0; i < 6; i++) {
out[i] = (ascii_to_hex(in[2 * i]) << 4) + ascii_to_hex(in[2 * i + 1]);
}
}
void tuya_ble_app_init(void)
{
device_param.device_id_len = 16; //If use the license stored by the SDK,initialized to 0, Otherwise 16 or 20.
uint8_t read_buf[16 + 32 + 6 + 1] = {0};
int ret = 0;
device_param.use_ext_license_key = 1;
if (device_param.device_id_len == 16) {
#if TUYA_INFO_TEST
memcpy(device_param.auth_key, (void *)auth_key_test, AUTH_KEY_LEN);
memcpy(device_param.device_id, (void *)device_id_test, DEVICE_ID_LEN);
memcpy(device_param.mac_addr.addr, mac_test, 6);
#else
ret = read_tuya_product_info_from_flash(read_buf, sizeof(read_buf));
if (ret == TRUE) {
uint8_t mac_data[6];
memcpy(device_param.device_id, read_buf, 16);
memcpy(device_param.auth_key, read_buf + 16, 32);
parse_mac_data(read_buf + 16 + 32, mac_data);
memcpy(device_param.mac_addr.addr, mac_data, 6);
}
#endif
device_param.mac_addr.addr_type = TUYA_BLE_ADDRESS_TYPE_RANDOM;
}
printf("device_id:");
put_buf(device_param.device_id, 16);
printf("auth_key:");
put_buf(device_param.auth_key, 32);
printf("mac:");
put_buf(device_param.mac_addr.addr, 6);
device_param.p_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
device_param.product_id_len = 8;
memcpy(device_param.product_id, APP_PRODUCT_ID, 8);
device_param.firmware_version = TY_APP_VER_NUM;
device_param.hardware_version = TY_HARD_VER_NUM;
printf("HJY:12345\n");
tuya_ble_sdk_init(&device_param);
ret = tuya_ble_callback_queue_register(tuya_cb_handler);
y_printf("tuya_ble_callback_queue_register,ret=%d\n", ret);
//tuya_ota_init();
//TUYA_APP_LOG_INFO("demo project version : "TUYA_BLE_DEMO_VERSION_STR);
TUYA_APP_LOG_INFO("app version : "TY_APP_VER_STR);
}

View File

@ -1,48 +0,0 @@
#ifndef TUYA_BLE_APP_DEMO_H_
#define TUYA_BLE_APP_DEMO_H_
#ifdef __cplusplus
extern "C" {
#endif
#define APP_PRODUCT_ID "xqhyt364"
#define APP_BUILD_FIRMNAME "tuya_ble_sdk_app_demo_nrf52832"
//固件版本
#define TY_APP_VER_NUM 0x0100
#define TY_APP_VER_STR "1.0"
//硬件版本
#define TY_HARD_VER_NUM 0x0100
#define TY_HARD_VER_STR "1.0"
/*
typedef enum {
white,
colour,
scene,
music,
} tuya_light_mode;
*/
void tuya_ble_app_init(void);
#ifdef __cplusplus
}
#endif
#endif //

View File

@ -1,207 +0,0 @@
#include "tuya_ota.h"
#include "tuya_ble_type.h"
#include "tuya_ble_app_demo.h"
#include "dual_bank_updata_api.h"
#include "timer.h"
#include "asm/clock.h"
extern u8 dual_bank_update_verify_without_crc(void);
tuya_ble_status_t tuya_ble_ota_response(tuya_ble_ota_response_t *p_data);
#define OTA_WRITE_FLASH_SIZE (2048)
typedef struct {
u32 file_size;
u32 recv_len;
u32 file_crc;
u16 tuya_ota_packet_num;
u8 buff[OTA_WRITE_FLASH_SIZE];
u32 buff_size;
} tuya_ota_t;
tuya_ota_t tuya_ota;
__attribute__((weak))
u8 tuya_start_ota_check(void)
{
return 0;
}
void tuya_ota_reset(void *priv)
{
cpu_reset();
}
int tuya_ota_boot_info_cb(int err)
{
sys_timeout_add(NULL, tuya_ota_reset, 2000);
return 0;
}
int tuya_ota_file_end_response(void *priv)
{
tuya_ble_ota_response_t response;
tuya_ota_end_response_t ota_end_response;
ota_end_response.reserve = 0;
int old_sys_clk = clk_get("sys");
clk_set("sys", 120 * 1000000L); //提升系统时钟提高校验速度
if (dual_bank_update_verify_without_crc() == 0) {
printf("UPDATE SUCCESS");
ota_end_response.state = 0;
dual_bank_update_burn_boot_info(tuya_ota_boot_info_cb);
} else {
printf("UPDATE FAILURE");
ota_end_response.state = 2;
}
clk_set("sys", old_sys_clk); //恢复时钟
response.type = TUYA_BLE_OTA_END;
response.p_data = &ota_end_response;
response.data_len = 2;
return tuya_ble_ota_response(&response);
}
int tuya_ota_data_response()
{
tuya_ble_ota_response_t response;
tuya_ota_data_response_t ota_data_response;
response.type = TUYA_BLE_OTA_DATA;
ota_data_response.reserve = 0;
ota_data_response.state = TUYA_OTA_DATA_SUCC;
response.p_data = &ota_data_response;
response.data_len = 2;
tuya_ble_ota_response(&response);
return 0;
}
int tuya_update_write_cb(void *priv)
{
tuya_ota_data_response();
return 0;
}
void tuya_ota_proc(u16 type, u8 *recv_data, u32 recv_len)
{
tuya_ble_ota_response_t response;
static bool first_packet_come = 0;
static u32 current_file_size = 0;
switch (type) {
case TUYA_BLE_OTA_REQ:
printf("TUYA_BLE_OTA_REQ\n");
dual_bank_passive_update_exit(NULL); //tuya APP退到后台会中断发数重新开始REQ要退出上一次的任务
tuya_ota_req_response_t ota_req_response;
ota_req_response.flag = tuya_start_ota_check();
ota_req_response.ota_version = 3;
ota_req_response.reserve = 0;
ota_req_response.frame_version = TY_APP_VER_NUM;
ota_req_response.max_pkt_len = OTA_MAX_DATA_LEN;
first_packet_come = 0;
current_file_size = 0;
response.p_data = &ota_req_response;
response.data_len = 9;
memset(&tuya_ota, 0, sizeof(tuya_ota));
break;
case TUYA_BLE_OTA_FILE_INFO:
printf("TUYA_BLE_OTA_FILE_INFO\n");
tuya_ota_file_info_response_t ota_file_info_response;
ota_file_info_response.reserve = 0;
tuya_ota.file_size = READ_BIG_U32(recv_data + 29);
uint32_t file_version = READ_BIG_U32(recv_data + 9);
printf("TUYA_BLE_OTA_FILE_INFO file_size%d file_version%d", tuya_ota.file_size, file_version);
dual_bank_passive_update_init(0, tuya_ota.file_size, OTA_WRITE_FLASH_SIZE, NULL);
if (dual_bank_update_allow_check(tuya_ota.file_size) != 0) {
dual_bank_passive_update_exit(NULL);
ota_file_info_response.state = TUYA_OTA_STATE_FILE_SIZE_TOO_LARGE;
} else if (file_version <= TY_APP_VER_NUM) {
dual_bank_passive_update_exit(NULL);
ota_file_info_response.state = TUYA_OTA_STATE_VER_LOW;
} else {
ota_file_info_response.state = TUYA_OTA_STATE_NORMAL;
}
response.p_data = &ota_file_info_response;
response.data_len = 26;
break;
case TUYA_BLE_OTA_FILE_OFFSET_REQ:
printf("TUYA_BLE_OTA_FILE_OFFSET_REQ\n");
uint8_t data[5] = {0};
response.type = TUYA_BLE_OTA_FILE_OFFSET_REQ;
u32 offset_addr = READ_BIG_U32(recv_data + 1);
data[1] = (u8)(offset_addr >> 24);
data[2] = (u8)(offset_addr >> 16);
data[3] = (u8)(offset_addr >> 8);
data[4] = (u8)(offset_addr >> 0);
printf("offset_addr = 0x%x", offset_addr);
response.data_len = 5;
response.p_data = data;
tuya_ble_ota_response(&response);
return;
/* tuya_ota_file_offset_response_t ota_file_offset_response; */
/* ota_file_offset_response.reserve = 0; */
/* ota_file_offset_response.offset = recv_data[1] << 24 | recv_data[2] << 16 | recv_data[3] << 8 | recv_data[4]; */
/* printf("offset:%d\n", ota_file_offset_response.offset); */
/* response.p_data = &ota_file_offset_response; */
/* response.data_len = 2; */
break;
case TUYA_BLE_OTA_DATA:
printf("TUYA_BLE_OTA_DATA\n");
tuya_ota_data_response_t ota_data_response;
ota_data_response.reserve = 0;
u16 remote_packet_num = (recv_data[1] << 8) + recv_data[2];
u32 cur_frame_size = (recv_data[3] << 8) + recv_data[4];
if (remote_packet_num == 0 && first_packet_come == 1) {
printf("OTA ERROR packet num error, num = %d", remote_packet_num);
ota_data_response.state = TUYA_OTA_DATA_PKT_NUM_ERR;
response.p_data = &ota_data_response;
response.data_len = 2;
response.type = TUYA_BLE_OTA_DATA;
tuya_ble_ota_response(&response);
return;
}
current_file_size += cur_frame_size;
printf("OTA DATA info:");
put_buf(recv_data, 7);
printf("file_size:%d remote_packet_num:%d, last_packet_num = %d, frame_size:%d\n", current_file_size, remote_packet_num, tuya_ota.tuya_ota_packet_num, recv_len - 7);
first_packet_come = 1;
if (remote_packet_num && remote_packet_num != tuya_ota.tuya_ota_packet_num + 1) {
printf("OTA ERROR packet num error");
ota_data_response.state = TUYA_OTA_DATA_PKT_NUM_ERR;
response.p_data = &ota_data_response;
response.data_len = 2;
tuya_ble_ota_response(&response);
//dual_bank_passive_update_exit(NULL);
return;
} else {
tuya_ota.recv_len += recv_len - 7;
memcpy(tuya_ota.buff + tuya_ota.buff_size, recv_data + 7, recv_len - 7);
tuya_ota.buff_size += recv_len - 7;
if (tuya_ota.buff_size >= OTA_WRITE_FLASH_SIZE) {
dual_bank_update_write(tuya_ota.buff, OTA_WRITE_FLASH_SIZE, tuya_update_write_cb);
tuya_ota.buff_size -= OTA_WRITE_FLASH_SIZE;
} else {
tuya_ota_data_response();
tuya_ota.tuya_ota_packet_num = remote_packet_num;
return;
}
}
tuya_ota.tuya_ota_packet_num = remote_packet_num;
break;
case TUYA_BLE_OTA_END:
printf("TUYA_BLE_OTA_END\n");
if (tuya_ota.buff_size != 0) { //把剩余的数据写入flash
dual_bank_update_write(tuya_ota.buff, tuya_ota.buff_size, tuya_ota_file_end_response);
} else {
tuya_ota_file_end_response(NULL);
}
break;
}
response.type = type;
tuya_ble_ota_response(&response);
}

View File

@ -1,58 +0,0 @@
#ifndef __TUYA_OTA_H__
#define __TUYA_OTA_H__
#include "typedef.h"
#define OTA_MAX_DATA_LEN 128
enum {
TUYA_OTA_STATE_NORMAL = 0,
TUYA_OTA_STATE_PID_NO_MATCH,
TUYA_OTA_STATE_VER_LOW,
TUYA_OTA_STATE_FILE_SIZE_TOO_LARGE,
};
enum {
TUYA_OTA_DATA_SUCC = 0,
TUYA_OTA_DATA_PKT_NUM_ERR,
TUYA_OTA_DATA_LEN_ERR,
TUYA_OTA_DATA_CRC_FAILED,
TUYA_OTA_DATA_OTHER_ERR,
};
#define READ_BIG_U32(a) ((*((u8*)(a)) <<24) + (*((u8*)(a)+1)<<16) + (*((u8*)(a)+2)<<8) + *((u8*)(a)+3))
typedef struct tuya_ota_req_response {
u8 flag;
u8 ota_version;
u8 reserve;
u32 frame_version;
u16 max_pkt_len;
} tuya_ota_req_response_t;
typedef struct tuya_ota_file_info_response {
u8 reserve;
u8 state;
u32 store_file_len; //用于断点续传,目前不支持
u32 store_crc;
u8 md5[16]; //目前不使用
} tuya_ota_file_info_response_t;
typedef struct tuya_ota_file_offset_response {
u8 reserve;
u32 offset;
} tuya_ota_file_offset_response_t;
typedef struct tuya_ota_data_response {
u8 reserve;
u8 state;
} tuya_ota_data_response_t;
typedef struct tuya_ota_end_response {
u8 reserve;
u8 state;
} tuya_ota_end_response_t;
void tuya_ota_proc(u16 type, u8 *recv_data, u32 recv_len);
#endif

View File

@ -1,100 +0,0 @@
/**
* \file tuya_ble_app_production_test.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef _TUYA_BLE_APP_PRODUCTION_TEST_H_
#define _TUYA_BLE_APP_PRODUCTION_TEST_H_
#include <stdint.h>
#include "tuya_ble_internal_config.h"
#ifdef __cplusplus
extern "C" {
#endif
#define TUYA_BLE_AUC_CMD_ENTER 0x00
#define TUYA_BLE_AUC_CMD_QUERY_HID 0x01
#define TUYA_BLE_AUC_CMD_GPIO_TEST 0x02
#define TUYA_BLE_AUC_CMD_WRITE_AUTH_INFO 0x03
#define TUYA_BLE_AUC_CMD_QUERY_INFO 0x04
#define TUYA_BLE_AUC_CMD_RESET 0x05
#define TUYA_BLE_AUC_CMD_QUERY_FINGERPRINT 0x06
#define TUYA_BLE_AUC_CMD_WRITE_HID 0x07
#define TUYA_BLE_AUC_CMD_RSSI_TEST 0x08
#define TUYA_BLE_AUC_CMD_WRITE_OEM_INFO 0x09
#define TUYA_BLE_AUC_CMD_WRITE_SUBPKG_START 0x0C
#define TUYA_BLE_AUC_CMD_WRITE_SUBPKG_END 0x0D
#define TUYA_BLE_AUC_CMD_WRITE_COMM_CFG 0x12 // ADD
#define TUYA_BLE_AUC_CMD_READ_MAC 0x13
#define TUYA_BLE_AUC_CMD_EXIT 0x14
#define TUYA_BLE_AUC_CMD_EXTEND 0xF0
#define TUYA_BLE_SDK_TEST_CMD_EXTEND 0xF2
#define TUYA_BLE_AUC_FINGERPRINT_VER 1
#if ( TUYA_BLE_PROD_SUPPORT_OEM_TYPE == TUYA_BLE_PROD_OEM_TYPE_0_5 )
#define TUYA_BLE_AUC_WRITE_PID 1
#else
#define TUYA_BLE_AUC_WRITE_PID 0
#endif
#define TUYA_BLE_AUC_WRITE_DEV_CERT 1
enum {
TUYA_BLE_AUC_FW_FINGERPRINT_POS = 0,
TUYA_BLE_AUC_WRITE_PID_POS = 1,
TUYA_BLE_AUC_WRITE_DEV_CERT_POS = 5,
};
/*channel: 0-uart ,1 - ble.*/
void tuya_ble_app_production_test_process(uint8_t channel, uint8_t *p_in_data, uint16_t in_len);
#if (TUYA_BLE_DEVICE_REGISTER_FROM_BLE&&TUYA_BLE_DEVICE_AUTH_DATA_STORE)
tuya_ble_status_t tuya_ble_prod_beacon_scan_start(void);
tuya_ble_status_t tuya_ble_prod_beacon_scan_stop(void);
tuya_ble_status_t tuya_ble_prod_beacon_get_rssi_avg(int8_t *rssi);
tuya_ble_status_t tuya_ble_prod_gpio_test(void);
void tuya_ble_internal_production_test_with_ble_flag_clear(void);
uint8_t tuya_ble_internal_production_test_with_ble_flag_get(void);
#endif
#ifdef __cplusplus
}
#endif
#endif // _TUYA_BLE_APP_PRODUCTION_TEST_H_

View File

@ -1,813 +0,0 @@
/**
* \file tuya_ble_app_uart_common_handler.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_main.h"
#include "tuya_ble_internal_config.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_mutli_tsf_protocol.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_secure.h"
#include "tuya_ble_main.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_app_uart_common_handler.h"
#include "tuya_ble_log.h"
#define TUYA_BLE_OTA_MCU_TEST 0
#define TUYA_BLE_UART_COMMON_MCU_OTA_DATA_LENGTH_MAX 200
#define TUYA_BLE_OTA_MCU_TYPE 1
#define TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST 0xEA
#define TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO 0xEB
#define TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET 0xEC
#define TUYA_BLE_UART_COMMON_MCU_OTA_DATA 0xED
#define TUYA_BLE_UART_COMMON_MCU_OTA_END 0xEE
#if (!TUYA_BLE_OTA_MCU_TEST)
void tuya_ble_uart_common_mcu_ota_data_from_ble_handler(uint16_t cmd, uint8_t *recv_data, uint32_t recv_len)
{
static uint8_t uart_data_temp[42];
uint8_t *uart_data_buffer = NULL;
uint8_t uart_data_len = 0;
if (cmd == FRM_OTA_DATA_REQ) {
uart_data_buffer = (uint8_t *)tuya_ble_malloc(recv_len + 7);
if (uart_data_buffer == NULL) {
TUYA_BLE_LOG_ERROR("uart_data_buffer malloc failed.");
return;
}
} else {
uart_data_buffer = uart_data_temp;
}
uart_data_buffer[0] = 0x55;
uart_data_buffer[1] = 0xAA;
uart_data_buffer[2] = 0x00;
switch (cmd) {
case FRM_OTA_START_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 2;
uart_data_buffer[6] = TUYA_BLE_UART_COMMON_MCU_OTA_DATA_LENGTH_MAX >> 8;
uart_data_buffer[7] = (uint8_t)TUYA_BLE_UART_COMMON_MCU_OTA_DATA_LENGTH_MAX;
uart_data_len = 8;
break;
case FRM_OTA_FILE_INFOR_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 35;
memcpy(uart_data_buffer + 6, recv_data, 8);
uart_data_buffer[14] = recv_data[9];
uart_data_buffer[15] = recv_data[10];
uart_data_buffer[16] = recv_data[11];
memcpy(&uart_data_buffer[17], recv_data + 12, 24);
uart_data_len = 41;
break;
case FRM_OTA_FILE_OFFSET_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 4;
memcpy(uart_data_buffer + 6, recv_data, 4);
uart_data_len = 10;
break;
case FRM_OTA_DATA_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_DATA;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = recv_len;
memcpy(uart_data_buffer + 6, recv_data, recv_len);
uart_data_len = 6 + recv_len;
break;
case FRM_OTA_END_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_END;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 0;
uart_data_len = 6;
break;
default:
break;
}
uart_data_buffer[uart_data_len] = tuya_ble_check_sum(uart_data_buffer, uart_data_len);
tuya_ble_common_uart_send_data(uart_data_buffer, uart_data_len + 1);
TUYA_BLE_LOG_HEXDUMP_DEBUG("mcu ota uart send data : ", uart_data_buffer, uart_data_len + 1);
if (cmd == FRM_OTA_DATA_REQ) {
tuya_ble_free(uart_data_buffer);
}
}
static void tuya_ble_uart_common_mcu_ota_data_from_uart_handler(uint8_t cmd, uint8_t *data_buffer, uint16_t data_len)
{
static uint8_t ble_data_buffer[30];
static uint8_t ble_data_len = 0;
uint16_t ble_cmd = 0;
tuya_ble_connect_status_t currnet_connect_status;
memset(ble_data_buffer, 0, sizeof(ble_data_buffer));
ble_data_len = 0;
switch (cmd) {
case TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST:
ble_data_buffer[0] = data_buffer[0];
ble_data_buffer[1] = 3;
ble_data_buffer[2] = TUYA_BLE_OTA_MCU_TYPE;
ble_data_buffer[3] = 0;
memcpy(&ble_data_buffer[4], data_buffer + 1, 5);
ble_data_len = 9;
ble_cmd = FRM_OTA_START_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
memcpy(&ble_data_buffer[1], data_buffer, 25);
ble_data_len = 26;
ble_cmd = FRM_OTA_FILE_INFOR_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
memcpy(&ble_data_buffer[1], data_buffer, 4);
ble_data_len = 5;
ble_cmd = FRM_OTA_FILE_OFFSET_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_DATA:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
ble_data_buffer[1] = data_buffer[0];
ble_data_len = 2;
ble_cmd = FRM_OTA_DATA_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_END:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
ble_data_buffer[1] = data_buffer[0];
ble_data_len = 2;
ble_cmd = FRM_OTA_END_RESP;
break;
default:
break;
};
currnet_connect_status = tuya_ble_connect_status_get();
if (currnet_connect_status != BONDING_CONN) {
TUYA_BLE_LOG_ERROR("tuya_ble_uart_common_mcu_ota_process FAILED.");
return;
}
if (ble_data_len > 0) {
tuya_ble_commData_send(ble_cmd, 0, ble_data_buffer, ble_data_len, ENCRYPTION_MODE_SESSION_KEY);
}
}
__TUYA_BLE_WEAK void tuya_ble_custom_app_uart_common_process(uint8_t *p_in_data, uint16_t in_len)
{
uint8_t cmd = p_in_data[3];
uint16_t data_len = (p_in_data[4] << 8) + p_in_data[5];
uint8_t *data_buffer = p_in_data + 6;
switch (cmd) {
default:
break;
};
}
void tuya_ble_uart_common_process(uint8_t *p_in_data, uint16_t in_len)
{
uint8_t cmd = p_in_data[3];
uint16_t data_len = (p_in_data[4] << 8) + p_in_data[5];
uint8_t *data_buffer = p_in_data + 6;
switch (cmd) {
case TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST:
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO:
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET:
case TUYA_BLE_UART_COMMON_MCU_OTA_DATA:
case TUYA_BLE_UART_COMMON_MCU_OTA_END:
tuya_ble_uart_common_mcu_ota_data_from_uart_handler(cmd, data_buffer, data_len);
break;
default:
tuya_ble_custom_app_uart_common_process(p_in_data, in_len);
break;
};
}
#else
tuya_ble_timer_t tuya_ble_xtimer_heartbeat ;
static uint32_t tuya_ble_heartbeat_timeout_ms = 1000;
static uint8_t heartbeat_uart_buffer[10];
static uint8_t mcu_info_get = 0;
static void tuya_ble_common_uart_protocol_send(uint8_t cmd, uint8_t *pdata, uint8_t len)
{
static uint8_t alloc_buf[256];
uint8_t i = 0;
alloc_buf[0 + 1] = 0x55;
alloc_buf[1 + 1] = 0xaa;
alloc_buf[2 + 1] = 0x00;
alloc_buf[3 + 1] = cmd;
alloc_buf[4 + 1] = 0;
alloc_buf[5 + 1] = len;
memcpy(alloc_buf + 6 + 1, pdata, len);
alloc_buf[7 + len] = tuya_ble_check_sum(alloc_buf + 1, 6 + len);
tuya_ble_common_uart_send_data(alloc_buf + 1, 7 + len);
}
static void tuya_ble_vtimer_heartbeat_callback(tuya_ble_timer_t timer)
{
heartbeat_uart_buffer[0] = 0x55;
heartbeat_uart_buffer[1] = 0xAA;
heartbeat_uart_buffer[2] = 0x00;
heartbeat_uart_buffer[3] = 0x00;
heartbeat_uart_buffer[4] = 0x00;
heartbeat_uart_buffer[5] = 0x00;
heartbeat_uart_buffer[6] = 0xFF;
tuya_ble_common_uart_send_data(heartbeat_uart_buffer, 7);
}
static void tuya_ble_heartbeat_timer_create(void)
{
if (tuya_ble_timer_create(&tuya_ble_xtimer_heartbeat, tuya_ble_heartbeat_timeout_ms, TUYA_BLE_TIMER_REPEATED, tuya_ble_vtimer_heartbeat_callback) != TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_ERROR("tuya_ble_xtimer_heartbeat creat failed");
}
}
static void tuya_ble_heartbeat_timer_start(void)
{
if (tuya_ble_timer_start(tuya_ble_xtimer_heartbeat) != TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_ERROR("tuya_ble_xtimer_heartbeat start failed");
}
}
static void tuya_ble_heartbeat_timer_restart(uint32_t ms)
{
if (tuya_ble_timer_restart(tuya_ble_xtimer_heartbeat, ms) != TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_ERROR("tuya_ble_xtimer_heartbeat restart failed");
}
}
static void tuya_ble_heartbeat_timer_stop(void)
{
if (tuya_ble_timer_stop(tuya_ble_xtimer_heartbeat) != TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_ERROR("tuya_ble_xtimer_heartbeat stop failed");
}
}
static void tuya_ble_heartbeat_timer_delete(void)
{
if (tuya_ble_timer_delete(tuya_ble_xtimer_heartbeat) != TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_ERROR("tuya_ble_xtimer_heartbeat delete failed");
}
}
static void tuya_ble_ota_data_process_test(uint8_t *p_data, uint16_t p_data_len);
void tuya_ble_uart_common_mcu_ota_data_from_ble_handler(uint16_t cmd, uint8_t *recv_data, uint32_t recv_len)
{
static uint8_t uart_data_temp[42];
uint8_t uart_cmd = 0xFF;
uint8_t *uart_data_buffer = NULL;
uint8_t uart_data_len = 0;
if (cmd == FRM_OTA_DATA_REQ) {
uart_data_buffer = (uint8_t *)tuya_ble_malloc(recv_len + 7);
if (uart_data_buffer == NULL) {
TUYA_BLE_LOG_ERROR("uart_data_buffer malloc failed.\n");
return;
}
} else {
uart_data_buffer = uart_data_temp;
}
uart_data_buffer[0] = 0x55;
uart_data_buffer[1] = 0xAA;
uart_data_buffer[2] = 0x00;
switch (cmd) {
case FRM_OTA_START_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 2;
uart_data_buffer[6] = TUYA_BLE_UART_COMMON_MCU_OTA_DATA_LENGTH_MAX >> 8;
uart_data_buffer[7] = (uint8_t)TUYA_BLE_UART_COMMON_MCU_OTA_DATA_LENGTH_MAX;
uart_data_len = 8;
break;
case FRM_OTA_FILE_INFOR_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 35;
memcpy(uart_data_buffer + 6, recv_data, 8);
uart_data_buffer[14] = recv_data[9];
uart_data_buffer[15] = recv_data[10];
uart_data_buffer[16] = recv_data[11];
memcpy(&uart_data_buffer[17], recv_data + 12, 24);
uart_data_len = 41;
break;
case FRM_OTA_FILE_OFFSET_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 4;
memcpy(uart_data_buffer + 6, recv_data, 4);
uart_data_len = 10;
break;
case FRM_OTA_DATA_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_DATA;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = recv_len;
memcpy(uart_data_buffer + 6, recv_data, recv_len);
uart_data_len = 6 + recv_len;
break;
case FRM_OTA_END_REQ:
uart_data_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_END;
uart_data_buffer[4] = 0;
uart_data_buffer[5] = 0;
uart_data_len = 6;
break;
default:
break;
}
uart_data_buffer[uart_data_len] = tuya_ble_check_sum(uart_data_buffer, uart_data_len);
tuya_ble_common_uart_send_data(uart_data_buffer, uart_data_len + 1);
TUYA_BLE_LOG_HEXDUMP_DEBUG("mcu ota uart send data : ", uart_data_buffer, uart_data_len + 1);
if (cmd == FRM_OTA_DATA_REQ) {
tuya_ble_free(uart_data_buffer);
}
}
static void tuya_ble_uart_common_mcu_ota_data_from_uart_handler(uint8_t cmd, uint8_t *data_buffer, uint16_t data_len)
{
static uint8_t ble_data_buffer[30];
static uint8_t ble_data_len = 0;
uint16_t ble_cmd = 0;
tuya_ble_connect_status_t currnet_connect_status;
memset(ble_data_buffer, 0, sizeof(ble_data_buffer));
ble_data_len = 0;
switch (cmd) {
case TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST:
ble_data_buffer[0] = data_buffer[0];
ble_data_buffer[1] = 3;
ble_data_buffer[2] = TUYA_BLE_OTA_MCU_TYPE;
ble_data_buffer[3] = 0;
memcpy(&ble_data_buffer[4], data_buffer + 1, 5);
ble_data_len = 9;
ble_cmd = FRM_OTA_START_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
memcpy(&ble_data_buffer[1], data_buffer, 25);
ble_data_len = 26;
ble_cmd = FRM_OTA_FILE_INFOR_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
memcpy(&ble_data_buffer[1], data_buffer, 4);
ble_data_len = 5;
ble_cmd = FRM_OTA_FILE_OFFSET_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_DATA:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
ble_data_buffer[1] = data_buffer[0];
ble_data_len = 2;
ble_cmd = FRM_OTA_DATA_RESP;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_END:
ble_data_buffer[0] = TUYA_BLE_OTA_MCU_TYPE;
ble_data_buffer[1] = data_buffer[0];
ble_data_len = 2;
ble_cmd = FRM_OTA_END_RESP;
break;
default:
break;
};
currnet_connect_status = tuya_ble_connect_status_get();
if (currnet_connect_status != BONDING_CONN) {
TUYA_BLE_LOG_ERROR("tuya_ble_uart_common_mcu_ota_process FAILED.");
return;
}
if (ble_data_len > 0) {
tuya_ble_commData_send(ble_cmd, 0, ble_data_buffer, ble_data_len, ENCRYPTION_MODE_SESSION_KEY);
}
}
void tuya_ble_uart_common_send_current_ble_state(void)
{
uint8_t ble_work_state = 0;
tuya_ble_connect_status_t ble_state;
ble_state = tuya_ble_connect_status_get();
if ((ble_state == UNBONDING_UNCONN) || (ble_state == UNBONDING_UNCONN) || (ble_state == UNBONDING_UNCONN)) {
ble_work_state = 1;
} else if ((ble_state == BONDING_UNCONN) || (ble_state == BONDING_UNAUTH_CONN)) {
ble_work_state = 2;
} else if (ble_state == BONDING_CONN) {
ble_work_state = 3;
} else {
ble_work_state = 0;
}
tuya_ble_common_uart_protocol_send(TUYA_BLE_UART_COMMON_REPORT_WORK_STATE_TYPE, (uint8_t *)&ble_work_state, 1);
}
void tuya_ble_uart_common_process(uint8_t *p_in_data, uint16_t in_len)
{
uint8_t cmd = p_in_data[3];
uint16_t data_len = (p_in_data[4] << 8) + p_in_data[5];
uint8_t *data_buffer = p_in_data + 6;
uint32_t mcu_firmware_version = 0, mcu_hardware_version = 0;
switch (cmd) {
case TUYA_BLE_UART_COMMON_HEART_MSG_TYPE:
if ((mcu_info_get == 0) || (data_buffer[0] == 0)) {
mcu_info_get = 1;
tuya_ble_common_uart_protocol_send(TUYA_BLE_UART_COMMON_SEARCH_PID_TYPE, NULL, 0);
}
break;
case TUYA_BLE_UART_COMMON_SEARCH_PID_TYPE:
if (memcmp(tuya_ble_current_para.pid, data_buffer, 8) != 0) {
TUYA_BLE_LOG_HEXDUMP_DEBUG("PID change to : ", data_buffer, 16);
tuya_ble_device_update_product_id(TUYA_BLE_PRODUCT_ID_TYPE_PID, 8, data_buffer);
}
tuya_ble_heartbeat_timer_restart(10000);
tuya_ble_common_uart_protocol_send(TUYA_BLE_UART_COMMON_CK_MCU_TYPE, NULL, 0);
tuya_ble_common_uart_protocol_send(TUYA_BLE_UART_COMMON_QUERY_MCU_VERSION, NULL, 0);
break;
case TUYA_BLE_UART_COMMON_CK_MCU_TYPE:
tuya_ble_uart_common_send_current_ble_state();
break;
case TUYA_BLE_UART_COMMON_QUERY_MCU_VERSION:
mcu_firmware_version = (data_buffer[0] << 16) | (data_buffer[1] << 8) | (data_buffer[2]);
mcu_hardware_version = (data_buffer[3] << 16) | (data_buffer[4] << 8) | (data_buffer[5]);
TUYA_BLE_LOG_DEBUG("reveived mcu_firmware_version : 0x%04x mcu_hardware_version : 0x%04x", mcu_firmware_version, mcu_hardware_version);
tuya_ble_device_update_mcu_version(mcu_firmware_version, mcu_hardware_version);
break;
case TUYA_BLE_UART_COMMON_MCU_SEND_VERSION:
mcu_firmware_version = (data_buffer[0] << 16) | (data_buffer[1] << 8) | (data_buffer[2]);
mcu_hardware_version = (data_buffer[3] << 16) | (data_buffer[4] << 8) | (data_buffer[5]);
TUYA_BLE_LOG_DEBUG("reveived mcu_firmware_version : 0x%04x mcu_hardware_version : 0x%04x", mcu_firmware_version, mcu_hardware_version);
tuya_ble_device_update_mcu_version(mcu_firmware_version, mcu_hardware_version);
break;
case TUYA_BLE_UART_COMMON_REPORT_WORK_STATE_TYPE:
break;
case TUYA_BLE_UART_COMMON_RESET_TYPE:
break;
case TUYA_BLE_UART_COMMON_SEND_CMD_TYPE:
break;
case TUYA_BLE_UART_COMMON_SEND_STATUS_TYPE:
break;
case TUYA_BLE_UART_COMMON_QUERY_STATUS:
break;
case TUYA_BLE_UART_COMMON_SEND_STORAGE_TYPE:
break;
case TUYA_BLE_UART_COMMON_SEND_TIME_SYNC_TYPE:
break;
case TUYA_BLE_UART_COMMON_MODIFY_ADV_INTERVAL:
break;
case TUYA_BLE_UART_COMMON_TURNOFF_SYSTEM_TIME:
break;
case TUYA_BLE_UART_COMMON_ENANBLE_LOWER_POWER:
break;
case TUYA_BLE_UART_COMMON_SEND_ONE_TIME_PASSWORD_TOKEN:
break;
case TUYA_BLE_UART_COMMON_ACTIVE_DISCONNECT:
break;
case TUYA_BLE_UART_COMMON_BLE_OTA_STATUS:
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST:
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO:
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET:
case TUYA_BLE_UART_COMMON_MCU_OTA_DATA:
case TUYA_BLE_UART_COMMON_MCU_OTA_END:
tuya_ble_uart_common_mcu_ota_data_from_uart_handler(cmd, data_buffer, data_len);
break;
default:
break;
};
}
static uint8_t mcu_ota_flag = 0;
#define MCU_OTA_MAX_DATA_SIZE 200
#define CURRENT_MCU_FIRMWARE_VERSION 0x010000
#define SUPPORT_MCU_OTA_FILE_MAX_LENGTH 102400
typedef struct {
uint32_t file_version;
uint8_t file_md5[16];
uint32_t file_length;
uint32_t file_crc32;
} mcu_ota_file_info_data_t;
static mcu_ota_file_info_data_t mcu_ota_file_data = {0};
static uint16_t current_package = 0;
static uint16_t last_package = 0;
static uint32_t current_image_crc_last;
static uint32_t current_image_write_offset;
static void mcu_ota_current_para_init(void)
{
current_package = 0;
last_package = 0;
mcu_ota_flag = 0;
current_image_crc_last = 0;
current_image_write_offset = 0;
}
void mcu_ota_test_init(void)
{
mcu_ota_current_para_init();
tuya_ble_heartbeat_timer_create();
tuya_ble_heartbeat_timer_start();
}
void mcu_ota_test_para_init_connect(void)
{
mcu_ota_current_para_init();
}
static void tuya_ble_ota_data_process_test(uint8_t *p_data, uint16_t p_data_len)
{
uint16_t len = 0;
uint16_t crc16_rev, crc16_temp;
static uint8_t ota_data_response_buffer[40];
uint8_t ota_data_response_len;
uint8_t cmd = p_data[3];
uint16_t ota_data_len = (p_data[4] << 8) + p_data[5];
uint8_t *ota_data_buffer = p_data + 6;
memset(ota_data_response_buffer, 0, sizeof(ota_data_response_buffer));
ota_data_response_buffer[0] = 0x55;
ota_data_response_buffer[1] = 0xaa;
ota_data_response_buffer[2] = 0x00;
switch (cmd) {
case TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST:
ota_data_response_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_REQUEST;
ota_data_response_buffer[4] = 0;
ota_data_response_buffer[5] = 6;
if (mcu_ota_flag == 0) {
mcu_ota_current_para_init();
ota_data_response_buffer[6] = 0;
ota_data_response_buffer[7] = ((uint32_t)CURRENT_MCU_FIRMWARE_VERSION >> 16);
ota_data_response_buffer[8] = ((uint32_t)CURRENT_MCU_FIRMWARE_VERSION >> 8);
ota_data_response_buffer[9] = ((uint32_t)CURRENT_MCU_FIRMWARE_VERSION);
ota_data_response_buffer[10] = ((uint16_t)MCU_OTA_MAX_DATA_SIZE >> 8);
ota_data_response_buffer[11] = ((uint16_t)MCU_OTA_MAX_DATA_SIZE);
mcu_ota_flag = 1;
memset(&mcu_ota_file_data, 0, sizeof(mcu_ota_file_data));
} else {
ota_data_response_buffer[6] = 1;
mcu_ota_flag = 0;
}
ota_data_response_len = 12;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO:
ota_data_response_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_FILE_INFO;
ota_data_response_buffer[4] = 0;
ota_data_response_buffer[5] = 25;
if (mcu_ota_flag != 1) {
ota_data_response_buffer[6] = 4;
mcu_ota_flag = 0;
} else {
if (memcmp(ota_data_buffer, tuya_ble_current_para.pid, 8)) {
ota_data_response_buffer[6] = 1;
mcu_ota_flag = 0;
} else {
mcu_ota_file_data.file_version = (ota_data_buffer[8] << 16) + (ota_data_buffer[9] << 8) + ota_data_buffer[10];
memcpy(mcu_ota_file_data.file_md5, ota_data_buffer + 11, 16);
mcu_ota_file_data.file_length = (ota_data_buffer[27] << 24) + (ota_data_buffer[28] << 16) + (ota_data_buffer[29] << 8) + ota_data_buffer[30];
mcu_ota_file_data.file_crc32 = (ota_data_buffer[31] << 24) + (ota_data_buffer[32] << 16) + (ota_data_buffer[33] << 8) + ota_data_buffer[34];
if (mcu_ota_file_data.file_version <= CURRENT_MCU_FIRMWARE_VERSION) {
ota_data_response_buffer[6] = 2;
mcu_ota_flag = 0;
} else if (mcu_ota_file_data.file_length > SUPPORT_MCU_OTA_FILE_MAX_LENGTH) {
ota_data_response_buffer[6] = 3;
mcu_ota_flag = 0;
} else {
ota_data_response_buffer[6] = 0;
mcu_ota_flag = 2;
}
}
}
ota_data_response_len = 31;
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET:
ota_data_response_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_FILE_OFFSET;
ota_data_response_buffer[4] = 0;
ota_data_response_buffer[5] = 4;
if (mcu_ota_flag == 2) {
memset(&ota_data_response_buffer[6], 0, 4);
mcu_ota_flag = 3;
ota_data_response_len = 10;
} else {
mcu_ota_flag = 0;
ota_data_response_len = 0;
}
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_DATA:
ota_data_response_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_DATA;
ota_data_response_buffer[4] = 0;
ota_data_response_buffer[5] = 1;
if ((mcu_ota_flag == 3) || (mcu_ota_flag == 4)) {
current_package = (ota_data_buffer[0] << 8) | ota_data_buffer[1];
len = (ota_data_buffer[2] << 8) | ota_data_buffer[3];
if ((current_package != (last_package + 1)) && (current_package != 0)) {
TUYA_BLE_LOG_ERROR("mcu ota received package number error.received package number : %d", current_package);
ota_data_response_buffer[6] = 1;
} else if ((len > MCU_OTA_MAX_DATA_SIZE) || ((len + 6) != (p_data_len - 7))) {
TUYA_BLE_LOG_ERROR("mcu ota received package data length error : len = %d,p_data_len = %d", len, p_data_len);
ota_data_response_buffer[6] = 2;
} else {
crc16_temp = (ota_data_buffer[4] << 8) | ota_data_buffer[5];
crc16_rev = tuya_ble_crc16_compute(&ota_data_buffer[6], len, NULL);
if (crc16_temp != crc16_rev) {
TUYA_BLE_LOG_ERROR("mcu ota received package data crc16 error,crc_16_cal = 0x%04x ; crc16_rev = 0x%04x", crc16_temp, crc16_rev);
ota_data_response_buffer[6] = 3;
}
}
if (ota_data_response_buffer[6] == 0) {
current_image_crc_last = tuya_ble_crc32_compute(&ota_data_buffer[6], len, &current_image_crc_last);
current_image_write_offset += len;
mcu_ota_flag = 4;
last_package = current_package;
} else {
mcu_ota_flag = 0;
mcu_ota_current_para_init();
}
ota_data_response_len = 7;
} else {
mcu_ota_flag = 0;
ota_data_response_len = 0;
}
break;
case TUYA_BLE_UART_COMMON_MCU_OTA_END:
ota_data_response_buffer[3] = TUYA_BLE_UART_COMMON_MCU_OTA_END;
ota_data_response_buffer[4] = 0;
ota_data_response_buffer[5] = 1;
if (mcu_ota_flag != 0) {
if (mcu_ota_file_data.file_length != current_image_write_offset) {
ota_data_response_buffer[6] = 1;
} else if (mcu_ota_file_data.file_crc32 != current_image_crc_last) {
ota_data_response_buffer[6] = 2;
} else {
ota_data_response_buffer[6] = 0;
mcu_ota_flag = 0;
TUYA_BLE_LOG_DEBUG("mcu ota test succeed.");
}
ota_data_response_len = 7;
} else {
mcu_ota_flag = 0;
ota_data_response_len = 0;
}
break;
default:
break;
};
if (ota_data_response_len > 0) {
ota_data_response_buffer[ota_data_response_len] = tuya_ble_check_sum(ota_data_response_buffer, ota_data_response_len);
ota_data_response_len++;
tuya_ble_common_uart_send_full_instruction_received(ota_data_response_buffer, ota_data_response_len);
}
}
#endif

View File

@ -1,53 +0,0 @@
/**
* \file tuya_ble_app_uart_common_handler.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef _TUYA_BLE_APP_UART_COMMON_HANDLER_H_
#define _TUYA_BLE_APP_UART_COMMON_HANDLER_H_
#include <stdint.h>
#include "tuya_ble_internal_config.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Function for transmit ble data from peer devices to tuya sdk.
*
* @note This function must be called from where the ble data is received.
*.
* */
void tuya_ble_uart_common_process(uint8_t *p_in_data, uint16_t in_len);
void tuya_ble_uart_common_mcu_ota_data_from_ble_handler(uint16_t cmd, uint8_t *recv_data, uint32_t recv_len);
#ifdef __cplusplus
}
#endif
#endif // _TUYA_BLE_APP_UART_COMMON_HANDLER_H_

View File

@ -1,678 +0,0 @@
/**
* \file aes.h
*
* \brief This file contains AES definitions and functions.
*
* The Advanced Encryption Standard (AES) specifies a FIPS-approved
* cryptographic algorithm that can be used to protect electronic
* data.
*
* The AES algorithm is a symmetric block cipher that can
* encrypt and decrypt information. For more information, see
* <em>FIPS Publication 197: Advanced Encryption Standard</em> and
* <em>ISO/IEC 18033-2:2006: Information technology -- Security
* techniques -- Encryption algorithms -- Part 2: Asymmetric
* ciphers</em>.
*
* The AES-XTS block mode is standardized by NIST SP 800-38E
* <https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38e.pdf>
* and described in detail by IEEE P1619
* <https://ieeexplore.ieee.org/servlet/opac?punumber=4375278>.
*/
/* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_AES_H
#define MBEDTLS_AES_H
#define MBEDTLS_AES_ROM_TABLES
//#define MBEDTLS_AES_FEWER_TABLES
#define MBEDTLS_CIPHER_MODE_CBC
//#define MBEDTLS_CIPHER_MODE_CFB
//#define MBEDTLS_PKCS1_V15
//#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
//#define MBEDTLS_SSL_PROTO_TLS1_1
/* mbed TLS modules */
#define MBEDTLS_AES_C
#include <stddef.h>
#include <stdint.h>
/* padlock.c and aesni.c rely on these values! */
#define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */
#define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */
/* Error codes in range 0x0020-0x0022 */
#define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */
#define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */
/* Error codes in range 0x0021-0x0025 */
#define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */
/* MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE is deprecated and should not be used. */
#define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */
/* MBEDTLS_ERR_AES_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_AES_ALT)
// Regular implementation
//
/**
* \brief The AES context-type definition.
*/
typedef struct mbedtls_aes_context {
int nr; /*!< The number of rounds. */
uint32_t *rk; /*!< AES round keys. */
uint32_t buf[68]; /*!< Unaligned data buffer. This buffer can
hold 32 extra Bytes, which can be used for
one of the following purposes:
<ul><li>Alignment if VIA padlock is
used.</li>
<li>Simplifying key expansion in the 256-bit
case by generating an extra round key.
</li></ul> */
}
mbedtls_aes_context;
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief The AES XTS context-type definition.
*/
typedef struct mbedtls_aes_xts_context {
mbedtls_aes_context crypt; /*!< The AES context to use for AES block
encryption or decryption. */
mbedtls_aes_context tweak; /*!< The AES context used for tweak
computation. */
} mbedtls_aes_xts_context;
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#else /* MBEDTLS_AES_ALT */
#include "aes_alt.h"
#endif /* MBEDTLS_AES_ALT */
/**
* \brief This function initializes the specified AES context.
*
* It must be the first API called before using
* the context.
*
* \param ctx The AES context to initialize. This must not be \c NULL.
*/
void mbedtls_aes_init(mbedtls_aes_context *ctx);
/**
* \brief This function releases and clears the specified AES context.
*
* \param ctx The AES context to clear.
* If this is \c NULL, this function does nothing.
* Otherwise, the context must have been at least initialized.
*/
void mbedtls_aes_free(mbedtls_aes_context *ctx);
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief This function initializes the specified AES XTS context.
*
* It must be the first API called before using
* the context.
*
* \param ctx The AES XTS context to initialize. This must not be \c NULL.
*/
void mbedtls_aes_xts_init(mbedtls_aes_xts_context *ctx);
/**
* \brief This function releases and clears the specified AES XTS context.
*
* \param ctx The AES XTS context to clear.
* If this is \c NULL, this function does nothing.
* Otherwise, the context must have been at least initialized.
*/
void mbedtls_aes_xts_free(mbedtls_aes_xts_context *ctx);
#endif /* MBEDTLS_CIPHER_MODE_XTS */
/**
* \brief This function sets the encryption key.
*
* \param ctx The AES context to which the key should be bound.
* It must be initialized.
* \param key The encryption key.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of data passed in bits. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key,
unsigned int keybits);
/**
* \brief This function sets the decryption key.
*
* \param ctx The AES context to which the key should be bound.
* It must be initialized.
* \param key The decryption key.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of data passed. Valid options are:
* <ul><li>128 bits</li>
* <li>192 bits</li>
* <li>256 bits</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key,
unsigned int keybits);
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief This function prepares an XTS context for encryption and
* sets the encryption key.
*
* \param ctx The AES XTS context to which the key should be bound.
* It must be initialized.
* \param key The encryption key. This is comprised of the XTS key1
* concatenated with the XTS key2.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of \p key passed in bits. Valid options are:
* <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>
* <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_xts_setkey_enc(mbedtls_aes_xts_context *ctx,
const unsigned char *key,
unsigned int keybits);
/**
* \brief This function prepares an XTS context for decryption and
* sets the decryption key.
*
* \param ctx The AES XTS context to which the key should be bound.
* It must be initialized.
* \param key The decryption key. This is comprised of the XTS key1
* concatenated with the XTS key2.
* This must be a readable buffer of size \p keybits bits.
* \param keybits The size of \p key passed in bits. Valid options are:
* <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>
* <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
*/
int mbedtls_aes_xts_setkey_dec(mbedtls_aes_xts_context *ctx,
const unsigned char *key,
unsigned int keybits);
#endif /* MBEDTLS_CIPHER_MODE_XTS */
/**
* \brief This function performs an AES single-block encryption or
* decryption operation.
*
* It performs the operation defined in the \p mode parameter
* (encrypt or decrypt), on the input data buffer defined in
* the \p input parameter.
*
* mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or
* mbedtls_aes_setkey_dec() must be called before the first
* call to this API with the same context.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param input The buffer holding the input data.
* It must be readable and at least \c 16 Bytes long.
* \param output The buffer where the output data will be written.
* It must be writeable and at least \c 16 Bytes long.
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16]);
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/**
* \brief This function performs an AES-CBC encryption or decryption operation
* on full blocks.
*
* It performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer defined in
* the \p input parameter.
*
* It can be called as many times as needed, until all the input
* data is processed. mbedtls_aes_init(), and either
* mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called
* before the first call to this API with the same context.
*
* \note This function operates on full blocks, that is, the input size
* must be a multiple of the AES block size of \c 16 Bytes.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the IV, you should
* either save it manually or use the cipher module instead.
*
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param length The length of the input data in Bytes. This must be a
* multiple of the block size (\c 16 Bytes).
* \param iv Initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
* on failure.
*/
int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output);
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
/**
* \brief This function performs an AES-XTS encryption or decryption
* operation for an entire XTS data unit.
*
* AES-XTS encrypts or decrypts blocks based on their location as
* defined by a data unit number. The data unit number must be
* provided by \p data_unit.
*
* NIST SP 800-38E limits the maximum size of a data unit to 2^20
* AES blocks. If the data unit is larger than this, this function
* returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH.
*
* \param ctx The AES XTS context to use for AES XTS operations.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param length The length of a data unit in Bytes. This can be any
* length between 16 bytes and 2^24 bytes inclusive
* (between 1 and 2^20 block cipher blocks).
* \param data_unit The address of the data unit encoded as an array of 16
* bytes in little-endian format. For disk encryption, this
* is typically the index of the block device sector that
* contains the data.
* \param input The buffer holding the input data (which is an entire
* data unit). This function reads \p length Bytes from \p
* input.
* \param output The buffer holding the output data (which is an entire
* data unit). This function writes \p length Bytes to \p
* output.
*
* \return \c 0 on success.
* \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is
* smaller than an AES block in size (16 Bytes) or if \p
* length is larger than 2^20 blocks (16 MiB).
*/
int mbedtls_aes_crypt_xts(mbedtls_aes_xts_context *ctx,
int mode,
size_t length,
const unsigned char data_unit[16],
const unsigned char *input,
unsigned char *output);
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
/**
* \brief This function performs an AES-CFB128 encryption or decryption
* operation.
*
* It performs the operation defined in the \p mode
* parameter (encrypt or decrypt), on the input data buffer
* defined in the \p input parameter.
*
* For CFB, you must set up the context with mbedtls_aes_setkey_enc(),
* regardless of whether you are performing an encryption or decryption
* operation, that is, regardless of the \p mode parameter. This is
* because CFB mode uses the same key schedule for encryption and
* decryption.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the
* IV, you must either save it manually or use the cipher
* module instead.
*
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT.
* \param length The length of the input data in Bytes.
* \param iv_off The offset in IV (updated after use).
* It must point to a valid \c size_t.
* \param iv The initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_cfb128(mbedtls_aes_context *ctx,
int mode,
size_t length,
size_t *iv_off,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output);
/**
* \brief This function performs an AES-CFB8 encryption or decryption
* operation.
*
* It performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer defined
* in the \p input parameter.
*
* Due to the nature of CFB, you must use the same key schedule for
* both encryption and decryption operations. Therefore, you must
* use the context initialized with mbedtls_aes_setkey_enc() for
* both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
*
* \note Upon exit, the content of the IV is updated so that you can
* call the same function again on the next
* block(s) of data and get the same result as if it was
* encrypted in one call. This allows a "streaming" usage.
* If you need to retain the contents of the
* IV, you should either save it manually or use the cipher
* module instead.
*
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
* #MBEDTLS_AES_DECRYPT
* \param length The length of the input data.
* \param iv The initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_cfb8(mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output);
#endif /*MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
/**
* \brief This function performs an AES-OFB (Output Feedback Mode)
* encryption or decryption operation.
*
* For OFB, you must set up the context with
* mbedtls_aes_setkey_enc(), regardless of whether you are
* performing an encryption or decryption operation. This is
* because OFB mode uses the same key schedule for encryption and
* decryption.
*
* The OFB operation is identical for encryption or decryption,
* therefore no operation mode needs to be specified.
*
* \note Upon exit, the content of iv, the Initialisation Vector, is
* updated so that you can call the same function again on the next
* block(s) of data and get the same result as if it was encrypted
* in one call. This allows a "streaming" usage, by initialising
* iv_off to 0 before the first call, and preserving its value
* between calls.
*
* For non-streaming use, the iv should be initialised on each call
* to a unique value, and iv_off set to 0 on each call.
*
* If you need to retain the contents of the initialisation vector,
* you must either save it manually or use the cipher module
* instead.
*
* \warning For the OFB mode, the initialisation vector must be unique
* every encryption operation. Reuse of an initialisation vector
* will compromise security.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param length The length of the input data.
* \param iv_off The offset in IV (updated after use).
* It must point to a valid \c size_t.
* \param iv The initialization vector (updated after use).
* It must be a readable and writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_ofb(mbedtls_aes_context *ctx,
size_t length,
size_t *iv_off,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output);
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/**
* \brief This function performs an AES-CTR encryption or decryption
* operation.
*
* This function performs the operation defined in the \p mode
* parameter (encrypt/decrypt), on the input data buffer
* defined in the \p input parameter.
*
* Due to the nature of CTR, you must use the same key schedule
* for both encryption and decryption operations. Therefore, you
* must use the context initialized with mbedtls_aes_setkey_enc()
* for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
*
* \warning You must never reuse a nonce value with the same key. Doing so
* would void the encryption for the two messages encrypted with
* the same nonce and key.
*
* There are two common strategies for managing nonces with CTR:
*
* 1. You can handle everything as a single message processed over
* successive calls to this function. In that case, you want to
* set \p nonce_counter and \p nc_off to 0 for the first call, and
* then preserve the values of \p nonce_counter, \p nc_off and \p
* stream_block across calls to this function as they will be
* updated by this function.
*
* With this strategy, you must not encrypt more than 2**128
* blocks of data with the same key.
*
* 2. You can encrypt separate messages by dividing the \p
* nonce_counter buffer in two areas: the first one used for a
* per-message nonce, handled by yourself, and the second one
* updated by this function internally.
*
* For example, you might reserve the first 12 bytes for the
* per-message nonce, and the last 4 bytes for internal use. In that
* case, before calling this function on a new message you need to
* set the first 12 bytes of \p nonce_counter to your chosen nonce
* value, the last 4 to 0, and \p nc_off to 0 (which will cause \p
* stream_block to be ignored). That way, you can encrypt at most
* 2**96 messages of up to 2**32 blocks each with the same key.
*
* The per-message nonce (or information sufficient to reconstruct
* it) needs to be communicated with the ciphertext and must be unique.
* The recommended way to ensure uniqueness is to use a message
* counter. An alternative is to generate random nonces, but this
* limits the number of messages that can be securely encrypted:
* for example, with 96-bit random nonces, you should not encrypt
* more than 2**32 messages with the same key.
*
* Note that for both stategies, sizes are measured in blocks and
* that an AES block is 16 bytes.
*
* \warning Upon return, \p stream_block contains sensitive data. Its
* content must not be written to insecure storage and should be
* securely discarded as soon as it's no longer needed.
*
* \param ctx The AES context to use for encryption or decryption.
* It must be initialized and bound to a key.
* \param length The length of the input data.
* \param nc_off The offset in the current \p stream_block, for
* resuming within the current cipher stream. The
* offset pointer should be 0 at the start of a stream.
* It must point to a valid \c size_t.
* \param nonce_counter The 128-bit nonce and counter.
* It must be a readable-writeable buffer of \c 16 Bytes.
* \param stream_block The saved stream block for resuming. This is
* overwritten by the function.
* It must be a readable-writeable buffer of \c 16 Bytes.
* \param input The buffer holding the input data.
* It must be readable and of size \p length Bytes.
* \param output The buffer holding the output data.
* It must be writeable and of size \p length Bytes.
*
* \return \c 0 on success.
*/
int mbedtls_aes_crypt_ctr(mbedtls_aes_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[16],
unsigned char stream_block[16],
const unsigned char *input,
unsigned char *output);
#endif /* MBEDTLS_CIPHER_MODE_CTR */
/**
* \brief Internal AES block encryption function. This is only
* exposed to allow overriding it using
* \c MBEDTLS_AES_ENCRYPT_ALT.
*
* \param ctx The AES context to use for encryption.
* \param input The plaintext block.
* \param output The output (ciphertext) block.
*
* \return \c 0 on success.
*/
int mbedtls_internal_aes_encrypt(mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16]);
/**
* \brief Internal AES block decryption function. This is only
* exposed to allow overriding it using see
* \c MBEDTLS_AES_DECRYPT_ALT.
*
* \param ctx The AES context to use for decryption.
* \param input The ciphertext block.
* \param output The output (plaintext) block.
*
* \return \c 0 on success.
*/
int mbedtls_internal_aes_decrypt(mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16]);
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Deprecated internal AES block encryption function
* without return value.
*
* \deprecated Superseded by mbedtls_internal_aes_encrypt()
*
* \param ctx The AES context to use for encryption.
* \param input Plaintext block.
* \param output Output (ciphertext) block.
*/
MBEDTLS_DEPRECATED void mbedtls_aes_encrypt(mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16]);
/**
* \brief Deprecated internal AES block decryption function
* without return value.
*
* \deprecated Superseded by mbedtls_internal_aes_decrypt()
*
* \param ctx The AES context to use for decryption.
* \param input Ciphertext block.
* \param output Output (plaintext) block.
*/
MBEDTLS_DEPRECATED void mbedtls_aes_decrypt(mbedtls_aes_context *ctx,
const unsigned char input[16],
unsigned char output[16]);
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if (MBEDTLS_SELF_TEST==1)
/**
* \brief Checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_aes_self_test(int verbose);
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* aes.h */

View File

@ -1,391 +0,0 @@
/*
* NIST SP800-38C compliant CCM implementation
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* Definition of CCM:
* http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
* RFC 3610 "Counter with CBC-MAC (CCM)"
*
* Related:
* RFC 5116 "An Interface and Algorithms for Authenticated Encryption"
*/
#include <string.h>
#include "aes.h"
#include "ccm.h"
#include "cpu.h"
#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1
static bool aes128_ecb_encrypt(const uint8_t *key, uint8_t *input, uint16_t input_len, uint8_t *output)
{
uint16_t length;
mbedtls_aes_context aes_ctx;
//
if (input_len % 16) {
return false;
}
length = input_len;
mbedtls_aes_init(&aes_ctx);
mbedtls_aes_setkey_enc(&aes_ctx, key, 128);
while (length > 0) {
mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, input, output);
input += 16;
output += 16;
length -= 16;
}
mbedtls_aes_free(&aes_ctx);
return true;
}
static int aes_ecb_encrypt(const uint8_t *pKey, uint8_t *input, uint8_t *output)
{
// return (int)aes128_ecb_encrypt(pKey, input, 16, output);
// AES128_ECB_encrypt(input,pKey, output);
// return 0;
// return aes128_encrypt(pKey, input, 16, output);
uint16_t length;
mbedtls_aes_context aes_ctx;
length = 16;
mbedtls_aes_init(&aes_ctx);
mbedtls_aes_setkey_enc(&aes_ctx, pKey, 128);
while (length > 0) {
mbedtls_aes_crypt_ecb(&aes_ctx, MBEDTLS_AES_ENCRYPT, input, output);
input += 16;
output += 16;
length -= 16;
}
mbedtls_aes_free(&aes_ctx);
return 0;
}
/* Implementation that should never be optimized out by the compiler */
static void mbedtls_zeroize(void *v, size_t n)
{
volatile unsigned char *p = v;
while (n--) {
*p++ = 0;
}
}
/*
* Macros for common operations.
* Results in smaller compiled code than static inline functions.
*/
/*
* Update the CBC-MAC state in y using a block in b
* (Always using b as the source helps the compiler optimise a bit better.)
*/
#define UPDATE_CBC_MAC \
for( i = 0; i < 16; i++ ) \
y[i] ^= b[i]; \
\
if( ( ret = aes_ecb_encrypt( key, y, y) ) != 0 ) \
return( ret );
/*
* Encrypt or decrypt a partial block with CTR
* Warning: using b for temporary storage! src and dst must not be b!
* This avoids allocating one more 16 bytes buffer while allowing src == dst.
*/
#define CTR_CRYPT( dst, src, len ) \
if( ( ret = aes_ecb_encrypt( key, ctr, b) ) != 0 ) \
return( ret ); \
\
for( i = 0; i < len; i++ ) \
dst[i] = src[i] ^ b[i];
/*
* Authenticated encryption or decryption
*/
static int ccm_auth_crypt(int mode, const unsigned char *key,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, size_t length,
unsigned char *output,
unsigned char *tag, size_t tag_len)
{
int ret;
unsigned char i;
unsigned char q;
size_t len_left;
unsigned char b[16];
unsigned char y[16];
unsigned char ctr[16];
const unsigned char *src;
unsigned char *dst;
/*
* Check length requirements: SP800-38C A.1
* Additional requirement: a < 2^16 - 2^8 to simplify the code.
* 'length' checked later (when writing it to the first block)
*/
if (tag_len < 4 || tag_len > 16 || tag_len % 2 != 0) {
return (MBEDTLS_ERR_CCM_BAD_INPUT);
}
/* Also implies q is within bounds */
if (iv_len < 7 || iv_len > 13) {
return (MBEDTLS_ERR_CCM_BAD_INPUT);
}
if (add_len > 0xFF00) {
return (MBEDTLS_ERR_CCM_BAD_INPUT);
}
q = 16 - 1 - (unsigned char) iv_len;
/*
* First block B_0:
* 0 .. 0 flags
* 1 .. iv_len nonce (aka iv)
* iv_len+1 .. 15 length
*
* With flags as (bits):
* 7 0
* 6 add present?
* 5 .. 3 (t - 2) / 2
* 2 .. 0 q - 1
*/
b[0] = 0;
b[0] |= (add_len > 0) << 6;
b[0] |= ((tag_len - 2) / 2) << 3;
b[0] |= q - 1;
memcpy(b + 1, iv, iv_len);
for (i = 0, len_left = length; i < q; i++, len_left >>= 8) {
b[15 - i] = (unsigned char)(len_left & 0xFF);
}
if (len_left > 0) {
return (MBEDTLS_ERR_CCM_BAD_INPUT);
}
/* Start CBC-MAC with first block */
memset(y, 0, 16);
UPDATE_CBC_MAC;
/*
* If there is additional data, update CBC-MAC with
* add_len, add, 0 (padding to a block boundary)
*/
if (add_len > 0) {
size_t use_len;
len_left = add_len;
src = add;
memset(b, 0, 16);
b[0] = (unsigned char)((add_len >> 8) & 0xFF);
b[1] = (unsigned char)((add_len) & 0xFF);
use_len = len_left < 16 - 2 ? len_left : 16 - 2;
memcpy(b + 2, src, use_len);
len_left -= use_len;
src += use_len;
UPDATE_CBC_MAC;
while (len_left > 0) {
use_len = len_left > 16 ? 16 : len_left;
memset(b, 0, 16);
memcpy(b, src, use_len);
UPDATE_CBC_MAC;
len_left -= use_len;
src += use_len;
}
}
/*
* Prepare counter block for encryption:
* 0 .. 0 flags
* 1 .. iv_len nonce (aka iv)
* iv_len+1 .. 15 counter (initially 1)
*
* With flags as (bits):
* 7 .. 3 0
* 2 .. 0 q - 1
*/
ctr[0] = q - 1;
memcpy(ctr + 1, iv, iv_len);
memset(ctr + 1 + iv_len, 0, q);
ctr[15] = 1;
/*
* Authenticate and {en,de}crypt the message.
*
* The only difference between encryption and decryption is
* the respective order of authentication and {en,de}cryption.
*/
len_left = length;
src = input;
dst = output;
while (len_left > 0) {
size_t use_len = len_left > 16 ? 16 : len_left;
if (mode == CCM_ENCRYPT) {
memset(b, 0, 16);
memcpy(b, src, use_len);
UPDATE_CBC_MAC;
}
CTR_CRYPT(dst, src, use_len);
if (mode == CCM_DECRYPT) {
memset(b, 0, 16);
memcpy(b, dst, use_len);
UPDATE_CBC_MAC;
}
dst += use_len;
src += use_len;
len_left -= use_len;
/*
* Increment counter.
* No need to check for overflow thanks to the length check above.
*/
for (i = 0; i < q; i++)
if (++ctr[15 - i] != 0) {
break;
}
}
/*
* Authentication: reset counter and crypt/mask internal tag
*/
for (i = 0; i < q; i++) {
ctr[15 - i] = 0;
}
CTR_CRYPT(y, y, 16);
memcpy(tag, y, tag_len);
return (0);
}
/*
* Authenticated encryption
*/
int aes_ccm_encrypt_and_tag(const unsigned char *key,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, size_t length,
unsigned char *output,
unsigned char *tag, size_t tag_len)
{
return (ccm_auth_crypt(CCM_ENCRYPT, key, iv, iv_len,
add, add_len, input, length, output, tag, tag_len));
}
/*
* Authenticated decryption
*/
int aes_ccm_auth_decrypt(const unsigned char *key,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, size_t length,
unsigned char *output,
const unsigned char *tag, size_t tag_len)
{
int ret;
unsigned char check_tag[16];
unsigned char i;
int diff;
if ((ret = ccm_auth_crypt(CCM_DECRYPT, key,
iv, iv_len, add, add_len,
input, length, output, check_tag, tag_len)) != 0) {
return (ret);
}
/* Check tag in "constant-time" */
for (diff = 0, i = 0; i < tag_len; i++) {
diff |= tag[i] ^ check_tag[i];
}
if (diff != 0) {
mbedtls_zeroize(output, length);
return (MBEDTLS_ERR_CCM_AUTH_FAILED);
}
return (0);
}
//#define MI_AUTOTEST
#ifdef MI_AUTOTEST
static uint8_t k[16] = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f
};
static uint8_t nonce[13] = {0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b, 0x1c
};
static uint8_t p[64] = "HELLOWORLD!@#$%^helloworld123456";
static uint8_t c[64] = {0};
static uint8_t d[64] = {0};
static uint8_t mic[4] = {0};
static uint8_t astr[4] = {1, 2, 3, 4};
#define LEN 32
void aes_ccm_test2(void)
{
aes_ccm_encrypt_and_tag(k, nonce, 12, astr, sizeof(astr), p, LEN, c, mic, 4);
aes_ccm_auth_decrypt(k, nonce, 12, astr, sizeof(astr), c, LEN, d, mic, 4);
//MI_LOG_INFO("Cipher : \n");
//MI_LOG_HEXDUMP(c, LEN);
// MI_LOG_INFO("MIC : \n");
// MI_LOG_HEXDUMP(mic, sizeof(mic));
// MI_LOG_DEBUG("AES128-CCM TEST: ");
if (memcmp(d, p, LEN) == 0) {
// MI_LOG_PRINTF(" PASS \n");
} else {
// MI_LOG_PRINTF(" FAIL \n");
}
}
#endif

View File

@ -1,93 +0,0 @@
/**
* \file ccm.h
*
* \brief Counter with CBC-MAC (CCM) for 128-bit block ciphers
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_CCM_H
#define MBEDTLS_CCM_H
#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to function. */
#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief CCM buffer encryption
*
* \param key key must be 16 bytes
* \param length length of the input data in bytes
* \param iv nonce (initialization vector)
* \param iv_len length of IV in bytes
* must be 2, 3, 4, 5, 6, 7 or 8
* \param add additional data
* \param add_len length of additional data in bytes
* must be less than 2^16 - 2^8
* \param input buffer holding the input data
* \param output buffer for holding the output data
* must be at least 'length' bytes wide
* \param tag buffer for holding the tag
* \param tag_len length of the tag to generate in bytes
* must be 4, 6, 8, 10, 14 or 16
*
* \note The tag is written to a separate buffer. To get the tag
* concatenated with the output as in the CCM spec, use
* tag = output + length and make sure the output buffer is
* at least length + tag_len wide.
*
* \return 0 if successful
*/
int aes_ccm_encrypt_and_tag(const unsigned char *key,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, size_t length,
unsigned char *output,
unsigned char *tag, size_t tag_len);
/**
* \brief CCM buffer authenticated decryption
*
* \param key key must be 16 bytes
* \param length length of the input data
* \param iv initialization vector
* \param iv_len length of IV
* \param add additional data
* \param add_len length of additional data
* \param input buffer holding the input data
* \param output buffer for holding the output data
* \param tag buffer holding the tag
* \param tag_len length of the tag
*
* \return 0 if successful and authenticated,
* MBEDTLS_ERR_CCM_AUTH_FAILED if tag does not match
*/
int aes_ccm_auth_decrypt(const unsigned char *key,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, size_t length,
unsigned char *output,
const unsigned char *tag, size_t tag_len);
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_CCM_H */

View File

@ -1,366 +0,0 @@
#include "sha1.h"
#include "sha256.h"
#include "hmac.h"
#define hmac_printf
#ifndef MIN
#define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
#ifndef CEIL_DIV
#define CEIL_DIV(a, b) (((a) + (b) - 1) / (b))
#endif
#define SHA1_DIGEST_SIZE 20
#define SHA1_BLOCK_SIZE 64
#define SHA256_DIGEST_SIZE 32
#define SHA256_BLOCK_SIZE 64
typedef struct {
/** Digest-specific context */
mbedtls_sha1_context *md_ctx;
/** HMAC part of the context */
uint8_t ipad[64];
uint8_t opad[64];
} hmac_sha1_context_t;
typedef struct {
/** Digest-specific context */
mbedtls_sha256_context *md_ctx;
/** HMAC part of the context */
uint8_t ipad[64];
uint8_t opad[64];
} hmac_sha256_context_t;
void hmac_sha1_init(hmac_sha1_context_t *ctx)
{
memset(ctx, 0, sizeof(hmac_sha1_context_t));
}
void hmac_sha1_free(hmac_sha1_context_t *ctx)
{
mbedtls_sha1_free((mbedtls_sha1_context *)ctx->md_ctx);
}
int32_t hmac_sha1_setup(hmac_sha1_context_t *ctx, int32_t hmac)
{
return 0;
}
int hmac_sha1_starts(hmac_sha1_context_t *ctx, const uint8_t *key, uint32_t keylen)
{
uint8_t sum[SHA1_DIGEST_SIZE];
uint32_t i;
if (keylen > (uint32_t) SHA1_BLOCK_SIZE) {
mbedtls_sha1_starts((mbedtls_sha1_context *) ctx->md_ctx);
mbedtls_sha1_update((mbedtls_sha1_context *) ctx->md_ctx, key, keylen);
mbedtls_sha1_finish((mbedtls_sha1_context *) ctx->md_ctx, sum);
keylen = SHA1_DIGEST_SIZE;
key = sum;
}
memset(ctx->ipad, 0x36, SHA1_BLOCK_SIZE);
memset(ctx->opad, 0x5C, SHA1_BLOCK_SIZE);
for (i = 0; i < keylen; i++) {
ctx->ipad[i] = (uint8_t)(ctx->ipad[i] ^ key[i]);
ctx->opad[i] = (uint8_t)(ctx->opad[i] ^ key[i]);
}
memset(sum, 0, sizeof(sum));
mbedtls_sha1_starts((mbedtls_sha1_context *) ctx->md_ctx);
mbedtls_sha1_update((mbedtls_sha1_context *) ctx->md_ctx, ctx->ipad, SHA1_BLOCK_SIZE);
return 0;
}
int32_t hmac_sha1_update(hmac_sha1_context_t *ctx, const uint8_t *input, uint32_t ilen)
{
mbedtls_sha1_update((mbedtls_sha1_context *) ctx->md_ctx, input, ilen);
return 0;
}
int32_t hmac_sha1_finish(hmac_sha1_context_t *ctx, uint8_t *output)
{
uint8_t tmp[SHA1_DIGEST_SIZE];
mbedtls_sha1_finish((mbedtls_sha1_context *) ctx->md_ctx, tmp);
mbedtls_sha1_starts((mbedtls_sha1_context *) ctx->md_ctx);
mbedtls_sha1_update((mbedtls_sha1_context *) ctx->md_ctx, ctx->opad, SHA1_BLOCK_SIZE);
mbedtls_sha1_update((mbedtls_sha1_context *) ctx->md_ctx, tmp, SHA1_DIGEST_SIZE);
mbedtls_sha1_finish((mbedtls_sha1_context *) ctx->md_ctx, output);
return 0;
}
int32_t hmac_sha1_reset(hmac_sha1_context_t *ctx)
{
mbedtls_sha1_starts((mbedtls_sha1_context *) ctx->md_ctx);
mbedtls_sha1_update((mbedtls_sha1_context *) ctx->md_ctx, ctx->ipad, SHA1_BLOCK_SIZE);
return 0 ;
}
int32_t hmac_sha1_crypt(const uint8_t *key, uint32_t keylen, const uint8_t *input, uint32_t ilen, uint8_t *output)
{
hmac_sha1_context_t ctx;
mbedtls_sha1_context sha_ctx;
int32_t ret;
hmac_sha1_init(&ctx);
memset(&sha_ctx, 0, sizeof(sha_ctx));
ctx.md_ctx = &sha_ctx;
if ((ret = hmac_sha1_setup(&ctx, 1)) != 0) {
return (ret);
}
hmac_sha1_starts(&ctx, key, keylen);
hmac_sha1_update(&ctx, input, ilen);
hmac_sha1_finish(&ctx, output);
return (0);
}
//
void hmac_sha256_init(hmac_sha256_context_t *ctx)
{
memset(ctx, 0, sizeof(hmac_sha256_context_t));
}
void hmac_sha256_free(hmac_sha256_context_t *ctx)
{
mbedtls_sha256_free((mbedtls_sha256_context *)ctx->md_ctx);
}
int32_t hmac_sha256_setup(hmac_sha256_context_t *ctx, int32_t hmac)
{
return 0;
}
int hmac_sha256_starts(hmac_sha256_context_t *ctx, const uint8_t *key, uint32_t keylen)
{
uint8_t sum[SHA256_DIGEST_SIZE];
uint32_t i;
if (keylen > (uint32_t) SHA256_BLOCK_SIZE) {
mbedtls_sha256_starts((mbedtls_sha256_context *) ctx->md_ctx, 0);
mbedtls_sha256_update((mbedtls_sha256_context *) ctx->md_ctx, key, keylen);
mbedtls_sha256_finish((mbedtls_sha256_context *) ctx->md_ctx, sum);
keylen = SHA256_DIGEST_SIZE;
key = sum;
}
memset(ctx->ipad, 0x36, SHA256_BLOCK_SIZE);
memset(ctx->opad, 0x5C, SHA256_BLOCK_SIZE);
for (i = 0; i < keylen; i++) {
ctx->ipad[i] = (uint8_t)(ctx->ipad[i] ^ key[i]);
ctx->opad[i] = (uint8_t)(ctx->opad[i] ^ key[i]);
}
memset(sum, 0, sizeof(sum));
mbedtls_sha256_starts((mbedtls_sha256_context *) ctx->md_ctx, 0);
mbedtls_sha256_update((mbedtls_sha256_context *) ctx->md_ctx, ctx->ipad, SHA256_BLOCK_SIZE);
return 0;
}
int32_t hmac_sha256_update(hmac_sha256_context_t *ctx, const uint8_t *input, uint32_t ilen)
{
mbedtls_sha256_update((mbedtls_sha256_context *) ctx->md_ctx, input, ilen);
return 0;
}
int32_t hmac_sha256_finish(hmac_sha256_context_t *ctx, uint8_t *output)
{
uint8_t tmp[SHA256_DIGEST_SIZE];
mbedtls_sha256_finish((mbedtls_sha256_context *) ctx->md_ctx, tmp);
mbedtls_sha256_starts((mbedtls_sha256_context *) ctx->md_ctx, 0);
mbedtls_sha256_update((mbedtls_sha256_context *) ctx->md_ctx, ctx->opad, SHA256_BLOCK_SIZE);
mbedtls_sha256_update((mbedtls_sha256_context *) ctx->md_ctx, tmp, SHA256_DIGEST_SIZE);
mbedtls_sha256_finish((mbedtls_sha256_context *) ctx->md_ctx, output);
return 0;
}
int32_t hmac_sha256_reset(hmac_sha256_context_t *ctx)
{
mbedtls_sha256_starts((mbedtls_sha256_context *) ctx->md_ctx, 0);
mbedtls_sha256_update((mbedtls_sha256_context *) ctx->md_ctx, ctx->ipad, SHA256_BLOCK_SIZE);
return 0 ;
}
int32_t hmac_sha256_crypt(const uint8_t *key, uint32_t keylen, const uint8_t *input, uint32_t ilen, uint8_t *output)
{
hmac_sha256_context_t ctx;
mbedtls_sha256_context sha_ctx;
int32_t ret;
hmac_sha256_init(&ctx);
memset(&sha_ctx, 0, sizeof(sha_ctx));
ctx.md_ctx = &sha_ctx;
if ((ret = hmac_sha256_setup(&ctx, 1)) != 0) {
return (ret);
}
hmac_sha256_starts(&ctx, key, keylen);
hmac_sha256_update(&ctx, input, ilen);
hmac_sha256_finish(&ctx, output);
return (0);
}
uint32_t sha256_hkdf(const uint8_t *key, uint32_t key_len,
const uint8_t *salt, uint32_t salt_len,
const uint8_t *info, uint32_t info_len,
uint8_t *out, uint32_t out_len)
{
const uint8_t null_salt[32] = {0};
uint8_t PRK[32];
uint8_t T_n[32];
uint32_t loop;
uint32_t temp_len;
// Step 1: HKDF-Extract(salt, IKM) -> PRK
if (salt == NULL) {
hmac_sha256_crypt(null_salt, 32, key, key_len, PRK);
} else {
hmac_sha256_crypt(salt, salt_len, key, key_len, PRK);
}
// Step 2: HKDF-Expand(PRK, info, L) -> OKM
//T(0) = empty string (zero length)
//T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
//T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
//T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
uint8_t temp[32 + info_len + 1];
memset(temp, 0, 32 + info_len + 1);
loop = CEIL_DIV(out_len, 32);
for (int32_t i = 0; i < loop ; i++) {
if (i == 0) {
temp_len = 0;
} else {
memcpy(temp, T_n, 32);
temp_len = 32;
}
memcpy(temp + temp_len, info, info_len);
temp_len += info_len;
temp[temp_len] = i + 1;
temp_len += 1;
hmac_sha256_crypt(PRK, 32, temp, temp_len, T_n);
memcpy(out + 32 * i, T_n, MIN(32, out_len));
out_len -= 32;
}
return 0;
}
/***************************************************this is for test************************************************/
#if (HMAC_SELF_TEST == 1)
///////////////////////////////////////////
//Hash = SHA-256
//IKM = 0x0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b (22 octets)
//salt = 0x000102030405060708090a0b0c (13 octets)
//info = 0xf0f1f2f3f4f5f6f7f8f9 (10 octets)
//L = 42
//
//PRK = 0x077709362c2e32df0ddc3f0dc47bba63
// 90b6c73bb50f9c3122ec844ad7c2b3e5 (32 octets)
//OKM = 0x3cb25f25faacd57a90434f64d0362f2a
// 2d2d0a90cf1a5a4c5db02d56ecc4c5bf
// 34007208d5b887185865 (42 octets)
#if 0
uint8_t salt[13] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c};
uint8_t info[10] = {0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9};
uint8_t key_material[22] = {0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b};
#endif
void hkdf_test(void)
{
uint8_t key_material[80] = {0x00,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f
};
uint8_t salt[80] = {0x60,
0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70,
0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80,
0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90,
0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0,
0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf
};
uint8_t info[80] = {0xb0,
0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0,
0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0,
0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0,
0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0,
0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
};
uint8_t expect[82] = {
0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 0xf7, 0x8c, 0x59, 0x6a, 0x49, 0x34,
0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf, 0xa9, 0x7c,
0x59, 0x04, 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59, 0x0e, 0x09,
0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77, 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71,
0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f,
0x1d, 0x87
};
uint8_t out_key[82];
sha256_hkdf(key_material, sizeof(key_material), salt, sizeof(salt), info, sizeof(info), out_key, 82);
hmac_printf("SHA256-HKDF TEST: ");
if (memcmp(expect, out_key, 82) == 0) {
hmac_printf(" PASS\n");
} else {
hmac_printf(" FAIL\n");
}
}
#endif

View File

@ -1,49 +0,0 @@
#ifndef HMAC_H
#define HMAC_H
#include <string.h>
#include <stddef.h>
#include <stdint.h>
#define HMAC_SELF_TEST 0
#ifdef __cplusplus
extern "C" {
#endif
/**
* \brief Output = Generic_HMAC( hmac key, input buffer )
*
* \param md_info message digest info
* \param key HMAC secret key
* \param keylen length of the HMAC key in bytes
* \param input buffer holding the data
* \param ilen length of the input data
* \param output Generic HMAC-result
*
* \returns 0 on success, MBEDTLS_ERR_MD_BAD_INPUT_DATA if parameter
* verification fails.
*/
int32_t hmac_sha1_crypt(const uint8_t *key, uint32_t keylen, const uint8_t *input, uint32_t ilen, uint8_t *output);
int32_t hmac_sha256_crypt(const uint8_t *key, uint32_t keylen, const uint8_t *input, uint32_t ilen, uint8_t *output);
uint32_t sha256_hkdf(const uint8_t *key, uint32_t key_len, const uint8_t *salt, uint32_t salt_len, const uint8_t *info, uint32_t info_len,
uint8_t *out, uint32_t out_len);
#if (HMAC_SELF_TEST == 1)
void hkdf_test(void);
#endif /* HMAC_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* hmac.h */

View File

@ -1,504 +0,0 @@
/*
* RFC 1321 compliant MD5 implementation
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* The MD5 algorithm was designed by Ron Rivest in 1991.
*
* http://www.ietf.org/rfc/rfc1321.txt
*/
#define MBEDTLS_MD5_C
#if defined(MBEDTLS_MD5_C)
#include "md5.h"
#include <string.h>
#define mbedtls_printf //printf
#if !defined(MBEDTLS_MD5_ALT)
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_UINT32_LE
#define GET_UINT32_LE(n,b,i) \
{ \
(n) = ( (uint32_t) (b)[(i) ] ) \
| ( (uint32_t) (b)[(i) + 1] << 8 ) \
| ( (uint32_t) (b)[(i) + 2] << 16 ) \
| ( (uint32_t) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_UINT32_LE
#define PUT_UINT32_LE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( ( (n) ) & 0xFF ); \
(b)[(i) + 1] = (unsigned char) ( ( (n) >> 8 ) & 0xFF ); \
(b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF ); \
(b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF ); \
}
#endif
void mbedtls_md5_init(mbedtls_md5_context *ctx)
{
memset(ctx, 0, sizeof(mbedtls_md5_context));
}
void mbedtls_md5_free(mbedtls_md5_context *ctx)
{
if (ctx == NULL) {
return;
}
//mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md5_context ) );
memset(ctx, 0, sizeof(mbedtls_md5_context));
}
void mbedtls_md5_clone(mbedtls_md5_context *dst,
const mbedtls_md5_context *src)
{
*dst = *src;
}
/*
* MD5 context setup
*/
int mbedtls_md5_starts_ret(mbedtls_md5_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;
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_starts(mbedtls_md5_context *ctx)
{
mbedtls_md5_starts_ret(ctx);
}
#endif
#if !defined(MBEDTLS_MD5_PROCESS_ALT)
int mbedtls_internal_md5_process(mbedtls_md5_context *ctx,
const unsigned char data[64])
{
uint32_t X[16], A, B, C, D;
GET_UINT32_LE(X[ 0], data, 0);
GET_UINT32_LE(X[ 1], data, 4);
GET_UINT32_LE(X[ 2], data, 8);
GET_UINT32_LE(X[ 3], data, 12);
GET_UINT32_LE(X[ 4], data, 16);
GET_UINT32_LE(X[ 5], data, 20);
GET_UINT32_LE(X[ 6], data, 24);
GET_UINT32_LE(X[ 7], data, 28);
GET_UINT32_LE(X[ 8], data, 32);
GET_UINT32_LE(X[ 9], data, 36);
GET_UINT32_LE(X[10], data, 40);
GET_UINT32_LE(X[11], data, 44);
GET_UINT32_LE(X[12], data, 48);
GET_UINT32_LE(X[13], data, 52);
GET_UINT32_LE(X[14], data, 56);
GET_UINT32_LE(X[15], data, 60);
#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n)))
#define P(a,b,c,d,k,s,t) \
{ \
a += F(b,c,d) + X[k] + t; a = S(a,s) + b; \
}
A = ctx->state[0];
B = ctx->state[1];
C = ctx->state[2];
D = ctx->state[3];
#define F(x,y,z) (z ^ (x & (y ^ z)))
P(A, B, C, D, 0, 7, 0xD76AA478);
P(D, A, B, C, 1, 12, 0xE8C7B756);
P(C, D, A, B, 2, 17, 0x242070DB);
P(B, C, D, A, 3, 22, 0xC1BDCEEE);
P(A, B, C, D, 4, 7, 0xF57C0FAF);
P(D, A, B, C, 5, 12, 0x4787C62A);
P(C, D, A, B, 6, 17, 0xA8304613);
P(B, C, D, A, 7, 22, 0xFD469501);
P(A, B, C, D, 8, 7, 0x698098D8);
P(D, A, B, C, 9, 12, 0x8B44F7AF);
P(C, D, A, B, 10, 17, 0xFFFF5BB1);
P(B, C, D, A, 11, 22, 0x895CD7BE);
P(A, B, C, D, 12, 7, 0x6B901122);
P(D, A, B, C, 13, 12, 0xFD987193);
P(C, D, A, B, 14, 17, 0xA679438E);
P(B, C, D, A, 15, 22, 0x49B40821);
#undef F
#define F(x,y,z) (y ^ (z & (x ^ y)))
P(A, B, C, D, 1, 5, 0xF61E2562);
P(D, A, B, C, 6, 9, 0xC040B340);
P(C, D, A, B, 11, 14, 0x265E5A51);
P(B, C, D, A, 0, 20, 0xE9B6C7AA);
P(A, B, C, D, 5, 5, 0xD62F105D);
P(D, A, B, C, 10, 9, 0x02441453);
P(C, D, A, B, 15, 14, 0xD8A1E681);
P(B, C, D, A, 4, 20, 0xE7D3FBC8);
P(A, B, C, D, 9, 5, 0x21E1CDE6);
P(D, A, B, C, 14, 9, 0xC33707D6);
P(C, D, A, B, 3, 14, 0xF4D50D87);
P(B, C, D, A, 8, 20, 0x455A14ED);
P(A, B, C, D, 13, 5, 0xA9E3E905);
P(D, A, B, C, 2, 9, 0xFCEFA3F8);
P(C, D, A, B, 7, 14, 0x676F02D9);
P(B, C, D, A, 12, 20, 0x8D2A4C8A);
#undef F
#define F(x,y,z) (x ^ y ^ z)
P(A, B, C, D, 5, 4, 0xFFFA3942);
P(D, A, B, C, 8, 11, 0x8771F681);
P(C, D, A, B, 11, 16, 0x6D9D6122);
P(B, C, D, A, 14, 23, 0xFDE5380C);
P(A, B, C, D, 1, 4, 0xA4BEEA44);
P(D, A, B, C, 4, 11, 0x4BDECFA9);
P(C, D, A, B, 7, 16, 0xF6BB4B60);
P(B, C, D, A, 10, 23, 0xBEBFBC70);
P(A, B, C, D, 13, 4, 0x289B7EC6);
P(D, A, B, C, 0, 11, 0xEAA127FA);
P(C, D, A, B, 3, 16, 0xD4EF3085);
P(B, C, D, A, 6, 23, 0x04881D05);
P(A, B, C, D, 9, 4, 0xD9D4D039);
P(D, A, B, C, 12, 11, 0xE6DB99E5);
P(C, D, A, B, 15, 16, 0x1FA27CF8);
P(B, C, D, A, 2, 23, 0xC4AC5665);
#undef F
#define F(x,y,z) (y ^ (x | ~z))
P(A, B, C, D, 0, 6, 0xF4292244);
P(D, A, B, C, 7, 10, 0x432AFF97);
P(C, D, A, B, 14, 15, 0xAB9423A7);
P(B, C, D, A, 5, 21, 0xFC93A039);
P(A, B, C, D, 12, 6, 0x655B59C3);
P(D, A, B, C, 3, 10, 0x8F0CCC92);
P(C, D, A, B, 10, 15, 0xFFEFF47D);
P(B, C, D, A, 1, 21, 0x85845DD1);
P(A, B, C, D, 8, 6, 0x6FA87E4F);
P(D, A, B, C, 15, 10, 0xFE2CE6E0);
P(C, D, A, B, 6, 15, 0xA3014314);
P(B, C, D, A, 13, 21, 0x4E0811A1);
P(A, B, C, D, 4, 6, 0xF7537E82);
P(D, A, B, C, 11, 10, 0xBD3AF235);
P(C, D, A, B, 2, 15, 0x2AD7D2BB);
P(B, C, D, A, 9, 21, 0xEB86D391);
#undef F
ctx->state[0] += A;
ctx->state[1] += B;
ctx->state[2] += C;
ctx->state[3] += D;
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_process(mbedtls_md5_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_md5_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_MD5_PROCESS_ALT */
/*
* MD5 process buffer
*/
int mbedtls_md5_update_ret(mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret;
size_t fill;
uint32_t left;
if (ilen == 0) {
return (0);
}
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);
if ((ret = mbedtls_internal_md5_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
input += fill;
ilen -= fill;
left = 0;
}
while (ilen >= 64) {
if ((ret = mbedtls_internal_md5_process(ctx, input)) != 0) {
return (ret);
}
input += 64;
ilen -= 64;
}
if (ilen > 0) {
memcpy((void *)(ctx->buffer + left), input, ilen);
}
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_update(mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_md5_update_ret(ctx, input, ilen);
}
#endif
/*
* MD5 final digest
*/
int mbedtls_md5_finish_ret(mbedtls_md5_context *ctx,
unsigned char output[16])
{
int ret;
uint32_t used;
uint32_t high, low;
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
*/
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if (used <= 56) {
/* Enough room for padding + length in current block */
memset(ctx->buffer + used, 0, 56 - used);
} else {
/* We'll need an extra block */
memset(ctx->buffer + used, 0, 64 - used);
if ((ret = mbedtls_internal_md5_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
memset(ctx->buffer, 0, 56);
}
/*
* Add message length
*/
high = (ctx->total[0] >> 29)
| (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
PUT_UINT32_LE(low, ctx->buffer, 56);
PUT_UINT32_LE(high, ctx->buffer, 60);
if ((ret = mbedtls_internal_md5_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
/*
* Output final state
*/
PUT_UINT32_LE(ctx->state[0], output, 0);
PUT_UINT32_LE(ctx->state[1], output, 4);
PUT_UINT32_LE(ctx->state[2], output, 8);
PUT_UINT32_LE(ctx->state[3], output, 12);
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5_finish(mbedtls_md5_context *ctx,
unsigned char output[16])
{
mbedtls_md5_finish_ret(ctx, output);
}
#endif
#endif /* !MBEDTLS_MD5_ALT */
/*
* output = MD5( input buffer )
*/
int mbedtls_md5_ret(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
int ret;
mbedtls_md5_context ctx;
mbedtls_md5_init(&ctx);
if ((ret = mbedtls_md5_starts_ret(&ctx)) != 0) {
goto exit;
}
if ((ret = mbedtls_md5_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if ((ret = mbedtls_md5_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_md5_free(&ctx);
return (ret);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md5(const unsigned char *input,
size_t ilen,
unsigned char output[16])
{
mbedtls_md5_ret(input, ilen, output);
}
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* RFC 1321 test vectors
*/
static const unsigned char md5_test_buf[7][81] = {
{ "" },
{ "a" },
{ "abc" },
{ "message digest" },
{ "abcdefghijklmnopqrstuvwxyz" },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" },
{
"12345678901234567890123456789012345678901234567890123456789012"
"345678901234567890"
}
};
static const size_t md5_test_buflen[7] = {
0, 1, 3, 14, 26, 62, 80
};
static const unsigned char md5_test_sum[7][16] = {
{
0xD4, 0x1D, 0x8C, 0xD9, 0x8F, 0x00, 0xB2, 0x04,
0xE9, 0x80, 0x09, 0x98, 0xEC, 0xF8, 0x42, 0x7E
},
{
0x0C, 0xC1, 0x75, 0xB9, 0xC0, 0xF1, 0xB6, 0xA8,
0x31, 0xC3, 0x99, 0xE2, 0x69, 0x77, 0x26, 0x61
},
{
0x90, 0x01, 0x50, 0x98, 0x3C, 0xD2, 0x4F, 0xB0,
0xD6, 0x96, 0x3F, 0x7D, 0x28, 0xE1, 0x7F, 0x72
},
{
0xF9, 0x6B, 0x69, 0x7D, 0x7C, 0xB7, 0x93, 0x8D,
0x52, 0x5A, 0x2F, 0x31, 0xAA, 0xF1, 0x61, 0xD0
},
{
0xC3, 0xFC, 0xD3, 0xD7, 0x61, 0x92, 0xE4, 0x00,
0x7D, 0xFB, 0x49, 0x6C, 0xCA, 0x67, 0xE1, 0x3B
},
{
0xD1, 0x74, 0xAB, 0x98, 0xD2, 0x77, 0xD9, 0xF5,
0xA5, 0x61, 0x1C, 0x2C, 0x9F, 0x41, 0x9D, 0x9F
},
{
0x57, 0xED, 0xF4, 0xA2, 0x2B, 0xE3, 0xC9, 0x55,
0xAC, 0x49, 0xDA, 0x2E, 0x21, 0x07, 0xB6, 0x7A
}
};
/*
* Checkup routine
*/
int mbedtls_md5_self_test(int verbose)
{
int i, ret = 0;
unsigned char md5sum[16];
for (i = 0; i < 7; i++) {
if (verbose != 0) {
mbedtls_printf(" MD5 test #%d: ", i + 1);
}
ret = mbedtls_md5_ret(md5_test_buf[i], md5_test_buflen[i], md5sum);
if (ret != 0) {
goto fail;
}
if (memcmp(md5sum, md5_test_sum[i], 16) != 0) {
ret = 1;
goto fail;
}
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if (verbose != 0) {
mbedtls_printf("\n");
}
return (0);
fail:
if (verbose != 0) {
mbedtls_printf("failed\n");
}
return (ret);
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_MD5_C */

View File

@ -1,309 +0,0 @@
/**
* \file md5.h
*
* \brief MD5 message digest algorithm (hash function)
*
* \warning MD5 is considered a weak message digest and its use constitutes a
* security risk. We recommend considering stronger message
* digests instead.
*/
/*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_MD5_H
#define MBEDTLS_MD5_H
#include <stddef.h>
#include <stdint.h>
//#define MBEDTLS_MD5_SELF_TEST
/* MBEDTLS_ERR_MD5_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_MD5_HW_ACCEL_FAILED -0x002F /**< MD5 hardware accelerator failed */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_MD5_ALT)
// Regular implementation
//
/**
* \brief MD5 context structure
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct mbedtls_md5_context {
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
}
mbedtls_md5_context;
#else /* MBEDTLS_MD5_ALT */
#include "md5_alt.h"
#endif /* MBEDTLS_MD5_ALT */
/**
* \brief Initialize MD5 context
*
* \param ctx MD5 context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_init(mbedtls_md5_context *ctx);
/**
* \brief Clear MD5 context
*
* \param ctx MD5 context to be cleared
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_free(mbedtls_md5_context *ctx);
/**
* \brief Clone (the state of) an MD5 context
*
* \param dst The destination context
* \param src The context to be cloned
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
void mbedtls_md5_clone(mbedtls_md5_context *dst,
const mbedtls_md5_context *src);
/**
* \brief MD5 context setup
*
* \param ctx context to be initialized
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_starts_ret(mbedtls_md5_context *ctx);
/**
* \brief MD5 process buffer
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param ilen length of the input data
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_update_ret(mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen);
/**
* \brief MD5 final digest
*
* \param ctx MD5 context
* \param output MD5 checksum result
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_finish_ret(mbedtls_md5_context *ctx,
unsigned char output[16]);
/**
* \brief MD5 process data block (internal use only)
*
* \param ctx MD5 context
* \param data buffer holding one block of data
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_internal_md5_process(mbedtls_md5_context *ctx,
const unsigned char data[64]);
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief MD5 context setup
*
* \deprecated Superseded by mbedtls_md5_starts_ret() in 2.7.0
*
* \param ctx context to be initialized
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_starts(mbedtls_md5_context *ctx);
/**
* \brief MD5 process buffer
*
* \deprecated Superseded by mbedtls_md5_update_ret() in 2.7.0
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param ilen length of the input data
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_update(mbedtls_md5_context *ctx,
const unsigned char *input,
size_t ilen);
/**
* \brief MD5 final digest
*
* \deprecated Superseded by mbedtls_md5_finish_ret() in 2.7.0
*
* \param ctx MD5 context
* \param output MD5 checksum result
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_finish(mbedtls_md5_context *ctx,
unsigned char output[16]);
/**
* \brief MD5 process data block (internal use only)
*
* \deprecated Superseded by mbedtls_internal_md5_process() in 2.7.0
*
* \param ctx MD5 context
* \param data buffer holding one block of data
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5_process(mbedtls_md5_context *ctx,
const unsigned char data[64]);
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief Output = MD5( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*
* \return 0 if successful
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_ret(const unsigned char *input,
size_t ilen,
unsigned char output[16]);
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief Output = MD5( input buffer )
*
* \deprecated Superseded by mbedtls_md5_ret() in 2.7.0
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
MBEDTLS_DEPRECATED void mbedtls_md5(const unsigned char *input,
size_t ilen,
unsigned char output[16]);
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SELF_TEST)
/**
* \brief Checkup routine
*
* \return 0 if successful, or 1 if the test failed
*
* \warning MD5 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
int mbedtls_md5_self_test(int verbose);
#endif /* MBEDTLS_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_md5.h */

View File

@ -1,575 +0,0 @@
/*
* FIPS-180-1 compliant SHA-1 implementation
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* The SHA-1 standard was published by NIST in 1993.
*
* http://www.itl.nist.gov/fipspubs/fip180-1.htm
*/
#define MBEDTLS_SHA1_C
#if defined(MBEDTLS_SHA1_C)
#include "sha1.h"
#include <string.h>
#define mbedtls_printf printf
/* Internal macros meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) do { } while( 0 )
#define MBEDTLS_INTERNAL_VALIDATE( cond ) do { } while( 0 )
#define SHA1_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA1_BAD_INPUT_DATA )
#define SHA1_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond )
#if !defined(MBEDTLS_SHA1_ALT)
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define 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 PUT_UINT32_BE
#define 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 mbedtls_sha1_init(mbedtls_sha1_context *ctx)
{
SHA1_VALIDATE(ctx != NULL);
memset(ctx, 0, sizeof(mbedtls_sha1_context));
}
void mbedtls_sha1_free(mbedtls_sha1_context *ctx)
{
if (ctx == NULL) {
return;
}
//mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha1_context ) );
memset(ctx, 0, sizeof(mbedtls_sha1_context));
}
void mbedtls_sha1_clone(mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src)
{
SHA1_VALIDATE(dst != NULL);
SHA1_VALIDATE(src != NULL);
*dst = *src;
}
/*
* SHA-1 context setup
*/
int mbedtls_sha1_starts_ret(mbedtls_sha1_context *ctx)
{
SHA1_VALIDATE_RET(ctx != NULL);
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;
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_starts(mbedtls_sha1_context *ctx)
{
mbedtls_sha1_starts_ret(ctx);
}
#endif
#if !defined(MBEDTLS_SHA1_PROCESS_ALT)
int mbedtls_internal_sha1_process(mbedtls_sha1_context *ctx,
const unsigned char data[64])
{
uint32_t temp, W[16], A, B, C, D, E;
SHA1_VALIDATE_RET(ctx != NULL);
SHA1_VALIDATE_RET((const unsigned char *)data != NULL);
GET_UINT32_BE(W[ 0], data, 0);
GET_UINT32_BE(W[ 1], data, 4);
GET_UINT32_BE(W[ 2], data, 8);
GET_UINT32_BE(W[ 3], data, 12);
GET_UINT32_BE(W[ 4], data, 16);
GET_UINT32_BE(W[ 5], data, 20);
GET_UINT32_BE(W[ 6], data, 24);
GET_UINT32_BE(W[ 7], data, 28);
GET_UINT32_BE(W[ 8], data, 32);
GET_UINT32_BE(W[ 9], data, 36);
GET_UINT32_BE(W[10], data, 40);
GET_UINT32_BE(W[11], data, 44);
GET_UINT32_BE(W[12], data, 48);
GET_UINT32_BE(W[13], data, 52);
GET_UINT32_BE(W[14], data, 56);
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;
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_process(mbedtls_sha1_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_sha1_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_SHA1_PROCESS_ALT */
/*
* SHA-1 process buffer
*/
int mbedtls_sha1_update_ret(mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret;
size_t fill;
uint32_t left;
SHA1_VALIDATE_RET(ctx != NULL);
SHA1_VALIDATE_RET(ilen == 0 || input != NULL);
if (ilen == 0) {
return (0);
}
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);
if ((ret = mbedtls_internal_sha1_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
input += fill;
ilen -= fill;
left = 0;
}
while (ilen >= 64) {
if ((ret = mbedtls_internal_sha1_process(ctx, input)) != 0) {
return (ret);
}
input += 64;
ilen -= 64;
}
if (ilen > 0) {
memcpy((void *)(ctx->buffer + left), input, ilen);
}
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_update(mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_sha1_update_ret(ctx, input, ilen);
}
#endif
/*
* SHA-1 final digest
*/
int mbedtls_sha1_finish_ret(mbedtls_sha1_context *ctx,
unsigned char output[20])
{
int ret;
uint32_t used;
uint32_t high, low;
SHA1_VALIDATE_RET(ctx != NULL);
SHA1_VALIDATE_RET((unsigned char *)output != NULL);
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
*/
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if (used <= 56) {
/* Enough room for padding + length in current block */
memset(ctx->buffer + used, 0, 56 - used);
} else {
/* We'll need an extra block */
memset(ctx->buffer + used, 0, 64 - used);
if ((ret = mbedtls_internal_sha1_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
memset(ctx->buffer, 0, 56);
}
/*
* Add message length
*/
high = (ctx->total[0] >> 29)
| (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
PUT_UINT32_BE(high, ctx->buffer, 56);
PUT_UINT32_BE(low, ctx->buffer, 60);
if ((ret = mbedtls_internal_sha1_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
/*
* Output final state
*/
PUT_UINT32_BE(ctx->state[0], output, 0);
PUT_UINT32_BE(ctx->state[1], output, 4);
PUT_UINT32_BE(ctx->state[2], output, 8);
PUT_UINT32_BE(ctx->state[3], output, 12);
PUT_UINT32_BE(ctx->state[4], output, 16);
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_finish(mbedtls_sha1_context *ctx,
unsigned char output[20])
{
mbedtls_sha1_finish_ret(ctx, output);
}
#endif
#endif /* !MBEDTLS_SHA1_ALT */
/*
* output = SHA-1( input buffer )
*/
int mbedtls_sha1_ret(const unsigned char *input,
size_t ilen,
unsigned char output[20])
{
int ret;
mbedtls_sha1_context ctx;
SHA1_VALIDATE_RET(ilen == 0 || input != NULL);
SHA1_VALIDATE_RET((unsigned char *)output != NULL);
mbedtls_sha1_init(&ctx);
if ((ret = mbedtls_sha1_starts_ret(&ctx)) != 0) {
goto exit;
}
if ((ret = mbedtls_sha1_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if ((ret = mbedtls_sha1_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_sha1_free(&ctx);
return (ret);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1(const unsigned char *input,
size_t ilen,
unsigned char output[20])
{
mbedtls_sha1_ret(input, ilen, output);
}
#endif
#if defined(MBEDTLS_SHA1_SELF_TEST)
/*
* FIPS-180-1 test vectors
*/
static const unsigned char sha1_test_buf[3][57] = {
{ "abc" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" },
{ "" }
};
static const size_t sha1_test_buflen[3] = {
3, 56, 1000
};
static const unsigned char sha1_test_sum[3][20] = {
{
0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E,
0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D
},
{
0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE,
0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1
},
{
0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E,
0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F
}
};
/*
* Checkup routine
*/
int mbedtls_sha1_self_test(int verbose)
{
int i, j, buflen, ret = 0;
unsigned char buf[1024];
unsigned char sha1sum[20];
mbedtls_sha1_context ctx;
mbedtls_sha1_init(&ctx);
/*
* SHA-1
*/
for (i = 0; i < 3; i++) {
if (verbose != 0) {
mbedtls_printf(" SHA-1 test #%d: ", i + 1);
}
if ((ret = mbedtls_sha1_starts_ret(&ctx)) != 0) {
goto fail;
}
if (i == 2) {
memset(buf, 'a', buflen = 1000);
for (j = 0; j < 1000; j++) {
ret = mbedtls_sha1_update_ret(&ctx, buf, buflen);
if (ret != 0) {
goto fail;
}
}
} else {
ret = mbedtls_sha1_update_ret(&ctx, sha1_test_buf[i],
sha1_test_buflen[i]);
if (ret != 0) {
goto fail;
}
}
if ((ret = mbedtls_sha1_finish_ret(&ctx, sha1sum)) != 0) {
goto fail;
}
if (memcmp(sha1sum, sha1_test_sum[i], 20) != 0) {
ret = 1;
goto fail;
}
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if (verbose != 0) {
mbedtls_printf("\n");
}
goto exit;
fail:
if (verbose != 0) {
mbedtls_printf("failed\n");
}
exit:
mbedtls_sha1_free(&ctx);
return (ret);
}
#endif /* MBEDTLS_SHA1_SELF_TEST */
#endif /* MBEDTLS_SHA1_C */

View File

@ -1,347 +0,0 @@
/**
* \file sha1.h
*
* \brief This file contains SHA-1 definitions and functions.
*
* The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in
* <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*
* \warning SHA-1 is considered a weak message digest and its use constitutes
* a security risk. We recommend considering stronger message
* digests instead.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_SHA1_H
#define MBEDTLS_SHA1_H
//#define MBEDTLS_SHA1_SELF_TEST
#include <stddef.h>
#include <stdint.h>
/* MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED -0x0035 /**< SHA-1 hardware accelerator failed */
#define MBEDTLS_ERR_SHA1_BAD_INPUT_DATA -0x0073 /**< SHA-1 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA1_ALT)
// Regular implementation
//
/**
* \brief The SHA-1 context structure.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
*/
typedef struct mbedtls_sha1_context {
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[5]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
}
mbedtls_sha1_context;
#else /* MBEDTLS_SHA1_ALT */
#include "sha1_alt.h"
#endif /* MBEDTLS_SHA1_ALT */
/**
* \brief This function initializes a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize.
* This must not be \c NULL.
*
*/
void mbedtls_sha1_init(mbedtls_sha1_context *ctx);
/**
* \brief This function clears a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to clear. This may be \c NULL,
* in which case this function does nothing. If it is
* not \c NULL, it must point to an initialized
* SHA-1 context.
*
*/
void mbedtls_sha1_free(mbedtls_sha1_context *ctx);
/**
* \brief This function clones the state of a SHA-1 context.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param dst The SHA-1 context to clone to. This must be initialized.
* \param src The SHA-1 context to clone from. This must be initialized.
*
*/
void mbedtls_sha1_clone(mbedtls_sha1_context *dst,
const mbedtls_sha1_context *src);
/**
* \brief This function starts a SHA-1 checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to initialize. This must be initialized.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_sha1_starts_ret(mbedtls_sha1_context *ctx);
/**
* \brief This function feeds an input buffer into an ongoing SHA-1
* checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha1_update_ret(mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen);
/**
* \brief This function finishes the SHA-1 operation, and writes
* the result to the output buffer.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to use. This must be initialized and
* have a hash operation started.
* \param output The SHA-1 checksum result. This must be a writable
* buffer of length \c 20 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha1_finish_ret(mbedtls_sha1_context *ctx,
unsigned char output[20]);
/**
* \brief SHA-1 process data block (internal use only).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param ctx The SHA-1 context to use. This must be initialized.
* \param data The data block being processed. This must be a
* readable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_internal_sha1_process(mbedtls_sha1_context *ctx,
const unsigned char data[64]);
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-1 checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_starts_ret() in 2.7.0.
*
* \param ctx The SHA-1 context to initialize. This must be initialized.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_starts(mbedtls_sha1_context *ctx);
/**
* \brief This function feeds an input buffer into an ongoing SHA-1
* checksum calculation.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_update_ret() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized and
* have a hash operation started.
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_update(mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen);
/**
* \brief This function finishes the SHA-1 operation, and writes
* the result to the output buffer.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_finish_ret() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized and
* have a hash operation started.
* \param output The SHA-1 checksum result.
* This must be a writable buffer of length \c 20 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_finish(mbedtls_sha1_context *ctx,
unsigned char output[20]);
/**
* \brief SHA-1 process data block (internal use only).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_internal_sha1_process() in 2.7.0.
*
* \param ctx The SHA-1 context. This must be initialized.
* \param data The data block being processed.
* This must be a readable buffer of length \c 64 bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1_process(mbedtls_sha1_context *ctx,
const unsigned char data[64]);
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief This function calculates the SHA-1 checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-1 result is calculated as
* output = SHA-1(input buffer).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
* \param output The SHA-1 checksum result.
* This must be a writable buffer of length \c 20 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*
*/
int mbedtls_sha1_ret(const unsigned char *input,
size_t ilen,
unsigned char output[20]);
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function calculates the SHA-1 checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-1 result is calculated as
* output = SHA-1(input buffer).
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \deprecated Superseded by mbedtls_sha1_ret() in 2.7.0
*
* \param input The buffer holding the input data.
* This must be a readable buffer of length \p ilen Bytes.
* \param ilen The length of the input data \p input in Bytes.
* \param output The SHA-1 checksum result. This must be a writable
* buffer of size \c 20 Bytes.
*
*/
MBEDTLS_DEPRECATED void mbedtls_sha1(const unsigned char *input,
size_t ilen,
unsigned char output[20]);
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SHA1_SELF_TEST)
/**
* \brief The SHA-1 checkup routine.
*
* \warning SHA-1 is considered a weak message digest and its use
* constitutes a security risk. We recommend considering
* stronger message digests instead.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*
*/
int mbedtls_sha1_self_test(int verbose);
#endif /* MBEDTLS_SHA1_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_sha1.h */

View File

@ -1,600 +0,0 @@
/*
* FIPS-180-2 compliant SHA-256 implementation
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* The SHA-256 Secure Hash Standard was published by NIST in 2002.
*
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
*/
#define MBEDTLS_SHA256_C
#if defined(MBEDTLS_SHA256_C)
#include "sha256.h"
#include <string.h>
#include <stdlib.h>
#define mbedtls_printf //printf
/* Internal macros meant to be called only from within the library. */
#define MBEDTLS_INTERNAL_VALIDATE_RET( cond, ret ) do { } while( 0 )
#define MBEDTLS_INTERNAL_VALIDATE( cond ) do { } while( 0 )
#define SHA256_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA256_BAD_INPUT_DATA )
#define SHA256_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond )
#if !defined(MBEDTLS_SHA256_ALT)
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) \
do { \
(n) = ( (uint32_t) (b)[(i) ] << 24 ) \
| ( (uint32_t) (b)[(i) + 1] << 16 ) \
| ( (uint32_t) (b)[(i) + 2] << 8 ) \
| ( (uint32_t) (b)[(i) + 3] ); \
} while( 0 )
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) \
do { \
(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) ); \
} while( 0 )
#endif
void mbedtls_sha256_init(mbedtls_sha256_context *ctx)
{
SHA256_VALIDATE(ctx != NULL);
memset(ctx, 0, sizeof(mbedtls_sha256_context));
}
void mbedtls_sha256_free(mbedtls_sha256_context *ctx)
{
if (ctx == NULL) {
return;
}
//mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha256_context ) );
memset(ctx, 0, sizeof(mbedtls_sha256_context));
}
void mbedtls_sha256_clone(mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src)
{
SHA256_VALIDATE(dst != NULL);
SHA256_VALIDATE(src != NULL);
*dst = *src;
}
/*
* SHA-256 context setup
*/
int mbedtls_sha256_starts_ret(mbedtls_sha256_context *ctx, int is224)
{
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET(is224 == 0 || is224 == 1);
ctx->total[0] = 0;
ctx->total[1] = 0;
if (is224 == 0) {
/* SHA-256 */
ctx->state[0] = 0x6A09E667;
ctx->state[1] = 0xBB67AE85;
ctx->state[2] = 0x3C6EF372;
ctx->state[3] = 0xA54FF53A;
ctx->state[4] = 0x510E527F;
ctx->state[5] = 0x9B05688C;
ctx->state[6] = 0x1F83D9AB;
ctx->state[7] = 0x5BE0CD19;
} else {
/* SHA-224 */
ctx->state[0] = 0xC1059ED8;
ctx->state[1] = 0x367CD507;
ctx->state[2] = 0x3070DD17;
ctx->state[3] = 0xF70E5939;
ctx->state[4] = 0xFFC00B31;
ctx->state[5] = 0x68581511;
ctx->state[6] = 0x64F98FA7;
ctx->state[7] = 0xBEFA4FA4;
}
ctx->is224 = is224;
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_starts(mbedtls_sha256_context *ctx,
int is224)
{
mbedtls_sha256_starts_ret(ctx, is224);
}
#endif
#if !defined(MBEDTLS_SHA256_PROCESS_ALT)
static const uint32_t K[] = {
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2,
};
#define SHR(x,n) ((x & 0xFFFFFFFF) >> n)
#define ROTR(x,n) (SHR(x,n) | (x << (32 - n)))
#define S0(x) (ROTR(x, 7) ^ ROTR(x,18) ^ SHR(x, 3))
#define S1(x) (ROTR(x,17) ^ ROTR(x,19) ^ SHR(x,10))
#define S2(x) (ROTR(x, 2) ^ ROTR(x,13) ^ ROTR(x,22))
#define S3(x) (ROTR(x, 6) ^ ROTR(x,11) ^ ROTR(x,25))
#define F0(x,y,z) ((x & y) | (z & (x | y)))
#define F1(x,y,z) (z ^ (x & (y ^ z)))
#define R(t) \
( \
W[t] = S1(W[t - 2]) + W[t - 7] + \
S0(W[t - 15]) + W[t - 16] \
)
#define P(a,b,c,d,e,f,g,h,x,K) \
{ \
temp1 = h + S3(e) + F1(e,f,g) + K + x; \
temp2 = S2(a) + F0(a,b,c); \
d += temp1; h = temp1 + temp2; \
}
int mbedtls_internal_sha256_process(mbedtls_sha256_context *ctx,
const unsigned char data[64])
{
uint32_t temp1, temp2, W[64];
uint32_t A[8];
unsigned int i;
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET((const unsigned char *)data != NULL);
for (i = 0; i < 8; i++) {
A[i] = ctx->state[i];
}
#if defined(MBEDTLS_SHA256_SMALLER)
for (i = 0; i < 64; i++) {
if (i < 16) {
GET_UINT32_BE(W[i], data, 4 * i);
} else {
R(i);
}
P(A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i], K[i]);
temp1 = A[7];
A[7] = A[6];
A[6] = A[5];
A[5] = A[4];
A[4] = A[3];
A[3] = A[2];
A[2] = A[1];
A[1] = A[0];
A[0] = temp1;
}
#else /* MBEDTLS_SHA256_SMALLER */
for (i = 0; i < 16; i++) {
GET_UINT32_BE(W[i], data, 4 * i);
}
for (i = 0; i < 16; i += 8) {
P(A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], W[i + 0], K[i + 0]);
P(A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], W[i + 1], K[i + 1]);
P(A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], W[i + 2], K[i + 2]);
P(A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], W[i + 3], K[i + 3]);
P(A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], W[i + 4], K[i + 4]);
P(A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], W[i + 5], K[i + 5]);
P(A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], W[i + 6], K[i + 6]);
P(A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], W[i + 7], K[i + 7]);
}
for (i = 16; i < 64; i += 8) {
P(A[0], A[1], A[2], A[3], A[4], A[5], A[6], A[7], R(i + 0), K[i + 0]);
P(A[7], A[0], A[1], A[2], A[3], A[4], A[5], A[6], R(i + 1), K[i + 1]);
P(A[6], A[7], A[0], A[1], A[2], A[3], A[4], A[5], R(i + 2), K[i + 2]);
P(A[5], A[6], A[7], A[0], A[1], A[2], A[3], A[4], R(i + 3), K[i + 3]);
P(A[4], A[5], A[6], A[7], A[0], A[1], A[2], A[3], R(i + 4), K[i + 4]);
P(A[3], A[4], A[5], A[6], A[7], A[0], A[1], A[2], R(i + 5), K[i + 5]);
P(A[2], A[3], A[4], A[5], A[6], A[7], A[0], A[1], R(i + 6), K[i + 6]);
P(A[1], A[2], A[3], A[4], A[5], A[6], A[7], A[0], R(i + 7), K[i + 7]);
}
#endif /* MBEDTLS_SHA256_SMALLER */
for (i = 0; i < 8; i++) {
ctx->state[i] += A[i];
}
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_process(mbedtls_sha256_context *ctx,
const unsigned char data[64])
{
mbedtls_internal_sha256_process(ctx, data);
}
#endif
#endif /* !MBEDTLS_SHA256_PROCESS_ALT */
/*
* SHA-256 process buffer
*/
int mbedtls_sha256_update_ret(mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen)
{
int ret;
size_t fill;
uint32_t left;
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET(ilen == 0 || input != NULL);
if (ilen == 0) {
return (0);
}
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);
if ((ret = mbedtls_internal_sha256_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
input += fill;
ilen -= fill;
left = 0;
}
while (ilen >= 64) {
if ((ret = mbedtls_internal_sha256_process(ctx, input)) != 0) {
return (ret);
}
input += 64;
ilen -= 64;
}
if (ilen > 0) {
memcpy((void *)(ctx->buffer + left), input, ilen);
}
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_update(mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen)
{
mbedtls_sha256_update_ret(ctx, input, ilen);
}
#endif
/*
* SHA-256 final digest
*/
int mbedtls_sha256_finish_ret(mbedtls_sha256_context *ctx,
unsigned char output[32])
{
int ret;
uint32_t used;
uint32_t high, low;
SHA256_VALIDATE_RET(ctx != NULL);
SHA256_VALIDATE_RET((unsigned char *)output != NULL);
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
*/
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if (used <= 56) {
/* Enough room for padding + length in current block */
memset(ctx->buffer + used, 0, 56 - used);
} else {
/* We'll need an extra block */
memset(ctx->buffer + used, 0, 64 - used);
if ((ret = mbedtls_internal_sha256_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
memset(ctx->buffer, 0, 56);
}
/*
* Add message length
*/
high = (ctx->total[0] >> 29)
| (ctx->total[1] << 3);
low = (ctx->total[0] << 3);
PUT_UINT32_BE(high, ctx->buffer, 56);
PUT_UINT32_BE(low, ctx->buffer, 60);
if ((ret = mbedtls_internal_sha256_process(ctx, ctx->buffer)) != 0) {
return (ret);
}
/*
* Output final state
*/
PUT_UINT32_BE(ctx->state[0], output, 0);
PUT_UINT32_BE(ctx->state[1], output, 4);
PUT_UINT32_BE(ctx->state[2], output, 8);
PUT_UINT32_BE(ctx->state[3], output, 12);
PUT_UINT32_BE(ctx->state[4], output, 16);
PUT_UINT32_BE(ctx->state[5], output, 20);
PUT_UINT32_BE(ctx->state[6], output, 24);
if (ctx->is224 == 0) {
PUT_UINT32_BE(ctx->state[7], output, 28);
}
return (0);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_finish(mbedtls_sha256_context *ctx,
unsigned char output[32])
{
mbedtls_sha256_finish_ret(ctx, output);
}
#endif
#endif /* !MBEDTLS_SHA256_ALT */
/*
* output = SHA-256( input buffer )
*/
int mbedtls_sha256_ret(const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224)
{
int ret;
mbedtls_sha256_context ctx;
SHA256_VALIDATE_RET(is224 == 0 || is224 == 1);
SHA256_VALIDATE_RET(ilen == 0 || input != NULL);
SHA256_VALIDATE_RET((unsigned char *)output != NULL);
mbedtls_sha256_init(&ctx);
if ((ret = mbedtls_sha256_starts_ret(&ctx, is224)) != 0) {
goto exit;
}
if ((ret = mbedtls_sha256_update_ret(&ctx, input, ilen)) != 0) {
goto exit;
}
if ((ret = mbedtls_sha256_finish_ret(&ctx, output)) != 0) {
goto exit;
}
exit:
mbedtls_sha256_free(&ctx);
return (ret);
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256(const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224)
{
mbedtls_sha256_ret(input, ilen, output, is224);
}
#endif
#if defined(MBEDTLS_SHA256_SELF_TEST)
#define mbedtls_calloc calloc
#define mbedtls_free free
/*
* FIPS-180-2 test vectors
*/
static const unsigned char sha256_test_buf[3][57] = {
{ "abc" },
{ "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" },
{ "" }
};
static const size_t sha256_test_buflen[3] = {
3, 56, 1000
};
static const unsigned char sha256_test_sum[6][32] = {
/*
* SHA-224 test vectors
*/
{
0x23, 0x09, 0x7D, 0x22, 0x34, 0x05, 0xD8, 0x22,
0x86, 0x42, 0xA4, 0x77, 0xBD, 0xA2, 0x55, 0xB3,
0x2A, 0xAD, 0xBC, 0xE4, 0xBD, 0xA0, 0xB3, 0xF7,
0xE3, 0x6C, 0x9D, 0xA7
},
{
0x75, 0x38, 0x8B, 0x16, 0x51, 0x27, 0x76, 0xCC,
0x5D, 0xBA, 0x5D, 0xA1, 0xFD, 0x89, 0x01, 0x50,
0xB0, 0xC6, 0x45, 0x5C, 0xB4, 0xF5, 0x8B, 0x19,
0x52, 0x52, 0x25, 0x25
},
{
0x20, 0x79, 0x46, 0x55, 0x98, 0x0C, 0x91, 0xD8,
0xBB, 0xB4, 0xC1, 0xEA, 0x97, 0x61, 0x8A, 0x4B,
0xF0, 0x3F, 0x42, 0x58, 0x19, 0x48, 0xB2, 0xEE,
0x4E, 0xE7, 0xAD, 0x67
},
/*
* SHA-256 test vectors
*/
{
0xBA, 0x78, 0x16, 0xBF, 0x8F, 0x01, 0xCF, 0xEA,
0x41, 0x41, 0x40, 0xDE, 0x5D, 0xAE, 0x22, 0x23,
0xB0, 0x03, 0x61, 0xA3, 0x96, 0x17, 0x7A, 0x9C,
0xB4, 0x10, 0xFF, 0x61, 0xF2, 0x00, 0x15, 0xAD
},
{
0x24, 0x8D, 0x6A, 0x61, 0xD2, 0x06, 0x38, 0xB8,
0xE5, 0xC0, 0x26, 0x93, 0x0C, 0x3E, 0x60, 0x39,
0xA3, 0x3C, 0xE4, 0x59, 0x64, 0xFF, 0x21, 0x67,
0xF6, 0xEC, 0xED, 0xD4, 0x19, 0xDB, 0x06, 0xC1
},
{
0xCD, 0xC7, 0x6E, 0x5C, 0x99, 0x14, 0xFB, 0x92,
0x81, 0xA1, 0xC7, 0xE2, 0x84, 0xD7, 0x3E, 0x67,
0xF1, 0x80, 0x9A, 0x48, 0xA4, 0x97, 0x20, 0x0E,
0x04, 0x6D, 0x39, 0xCC, 0xC7, 0x11, 0x2C, 0xD0
}
};
/*
* Checkup routine
*/
int mbedtls_sha256_self_test(int verbose)
{
int i, j, k, buflen, ret = 0;
unsigned char *buf;
unsigned char sha256sum[32];
mbedtls_sha256_context ctx;
buf = mbedtls_calloc(1024, sizeof(unsigned char));
if (NULL == buf) {
if (verbose != 0) {
mbedtls_printf("Buffer allocation failed\n");
}
return (1);
}
mbedtls_sha256_init(&ctx);
for (i = 0; i < 6; i++) {
j = i % 3;
k = i < 3;
if (verbose != 0) {
mbedtls_printf(" SHA-%d test #%d: ", 256 - k * 32, j + 1);
}
if ((ret = mbedtls_sha256_starts_ret(&ctx, k)) != 0) {
goto fail;
}
if (j == 2) {
memset(buf, 'a', buflen = 1000);
for (j = 0; j < 1000; j++) {
ret = mbedtls_sha256_update_ret(&ctx, buf, buflen);
if (ret != 0) {
goto fail;
}
}
} else {
ret = mbedtls_sha256_update_ret(&ctx, sha256_test_buf[j],
sha256_test_buflen[j]);
if (ret != 0) {
goto fail;
}
}
if ((ret = mbedtls_sha256_finish_ret(&ctx, sha256sum)) != 0) {
goto fail;
}
if (memcmp(sha256sum, sha256_test_sum[i], 32 - k * 4) != 0) {
ret = 1;
goto fail;
}
if (verbose != 0) {
mbedtls_printf("passed\n");
}
}
if (verbose != 0) {
mbedtls_printf("\n");
}
goto exit;
fail:
if (verbose != 0) {
mbedtls_printf("failed\n");
}
exit:
mbedtls_sha256_free(&ctx);
mbedtls_free(buf);
return (ret);
}
#endif /* MBEDTLS_SHA256_SELF_TEST */
#endif /* MBEDTLS_SHA256_C */

View File

@ -1,292 +0,0 @@
/**
* \file sha256.h
*
* \brief This file contains SHA-224 and SHA-256 definitions and functions.
*
* The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic
* hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
*/
/*
* Copyright (C) 2006-2018, Arm Limited (or its affiliates), All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_SHA256_H
#define MBEDTLS_SHA256_H
#include <stddef.h>
#include <stdint.h>
//#define MBEDTLS_SHA256_SELF_TEST
/* MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED is deprecated and should not be used. */
#define MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED -0x0037 /**< SHA-256 hardware accelerator failed */
#define MBEDTLS_ERR_SHA256_BAD_INPUT_DATA -0x0074 /**< SHA-256 input data was malformed. */
#ifdef __cplusplus
extern "C" {
#endif
#if !defined(MBEDTLS_SHA256_ALT)
// Regular implementation
//
/**
* \brief The SHA-256 context structure.
*
* The structure is used both for SHA-256 and for SHA-224
* checksum calculations. The choice between these two is
* made in the call to mbedtls_sha256_starts_ret().
*/
typedef struct mbedtls_sha256_context {
uint32_t total[2]; /*!< The number of Bytes processed. */
uint32_t state[8]; /*!< The intermediate digest state. */
unsigned char buffer[64]; /*!< The data block being processed. */
int is224; /*!< Determines which function to use:
0: Use SHA-256, or 1: Use SHA-224. */
}
mbedtls_sha256_context;
#else /* MBEDTLS_SHA256_ALT */
#include "sha256_alt.h"
#endif /* MBEDTLS_SHA256_ALT */
/**
* \brief This function initializes a SHA-256 context.
*
* \param ctx The SHA-256 context to initialize. This must not be \c NULL.
*/
void mbedtls_sha256_init(mbedtls_sha256_context *ctx);
/**
* \brief This function clears a SHA-256 context.
*
* \param ctx The SHA-256 context to clear. This may be \c NULL, in which
* case this function returns immediately. If it is not \c NULL,
* it must point to an initialized SHA-256 context.
*/
void mbedtls_sha256_free(mbedtls_sha256_context *ctx);
/**
* \brief This function clones the state of a SHA-256 context.
*
* \param dst The destination context. This must be initialized.
* \param src The context to clone. This must be initialized.
*/
void mbedtls_sha256_clone(mbedtls_sha256_context *dst,
const mbedtls_sha256_context *src);
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \param ctx The context to use. This must be initialized.
* \param is224 This determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_starts_ret(mbedtls_sha256_context *ctx, int is224);
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_update_ret(mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen);
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \param ctx The SHA-256 context. This must be initialized
* and have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result.
* This must be a writable buffer of length \c 32 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_sha256_finish_ret(mbedtls_sha256_context *ctx,
unsigned char output[32]);
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must
* be a readable buffer of length \c 64 Bytes.
*
* \return \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_internal_sha256_process(mbedtls_sha256_context *ctx,
const unsigned char data[64]);
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function starts a SHA-224 or SHA-256 checksum
* calculation.
*
* \deprecated Superseded by mbedtls_sha256_starts_ret() in 2.7.0.
*
* \param ctx The context to use. This must be initialized.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_starts(mbedtls_sha256_context *ctx,
int is224);
/**
* \brief This function feeds an input buffer into an ongoing
* SHA-256 checksum calculation.
*
* \deprecated Superseded by mbedtls_sha256_update_ret() in 2.7.0.
*
* \param ctx The SHA-256 context to use. This must be
* initialized and have a hash operation started.
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_update(mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen);
/**
* \brief This function finishes the SHA-256 operation, and writes
* the result to the output buffer.
*
* \deprecated Superseded by mbedtls_sha256_finish_ret() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized and
* have a hash operation started.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_finish(mbedtls_sha256_context *ctx,
unsigned char output[32]);
/**
* \brief This function processes a single data block within
* the ongoing SHA-256 computation. This function is for
* internal use only.
*
* \deprecated Superseded by mbedtls_internal_sha256_process() in 2.7.0.
*
* \param ctx The SHA-256 context. This must be initialized.
* \param data The buffer holding one block of data. This must be
* a readable buffer of size \c 64 Bytes.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256_process(mbedtls_sha256_context *ctx,
const unsigned char data[64]);
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
/**
* \brief This function calculates the SHA-224 or SHA-256
* checksum of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must
* be a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be
* either \c 0 for SHA-256, or \c 1 for SHA-224.
*/
int mbedtls_sha256_ret(const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224);
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
#if defined(MBEDTLS_DEPRECATED_WARNING)
#define MBEDTLS_DEPRECATED __attribute__((deprecated))
#else
#define MBEDTLS_DEPRECATED
#endif
/**
* \brief This function calculates the SHA-224 or SHA-256 checksum
* of a buffer.
*
* The function allocates the context, performs the
* calculation, and frees the context.
*
* The SHA-256 result is calculated as
* output = SHA-256(input buffer).
*
* \deprecated Superseded by mbedtls_sha256_ret() in 2.7.0.
*
* \param input The buffer holding the data. This must be a readable
* buffer of length \p ilen Bytes.
* \param ilen The length of the input data in Bytes.
* \param output The SHA-224 or SHA-256 checksum result. This must be
* a writable buffer of length \c 32 Bytes.
* \param is224 Determines which function to use. This must be either
* \c 0 for SHA-256, or \c 1 for SHA-224.
*/
MBEDTLS_DEPRECATED void mbedtls_sha256(const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224);
#undef MBEDTLS_DEPRECATED
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
#if defined(MBEDTLS_SHA256_SELF_TEST)
/**
* \brief The SHA-224 and SHA-256 checkup routine.
*
* \return \c 0 on success.
* \return \c 1 on failure.
*/
int mbedtls_sha256_self_test(int verbose);
#endif /* MBEDTLS_SHA256_SELF_TEST */
#ifdef __cplusplus
}
#endif
#endif /* mbedtls_sha256.h */

View File

@ -1,667 +0,0 @@
/**
* \file tuya_ble_port.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_port.h"
#include "tuya_ble_type.h"
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_gap_advertising_adv_data_update(uint8_t const *p_ad_data, uint8_t ad_len)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_gap_advertising_scan_rsp_data_update(uint8_t const *p_sr_data, uint8_t sr_len)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief Function for update the device information characteristic value.
*@param[in] p_data The pointer to the data to be updated.
*@param[in] data_len The length of the data to be updated.
*
*@note The device information characteristic uuid : 00000003-0000-1001-8001-00805F9B07D0
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_device_info_characteristic_value_update(uint8_t const *p_data, uint8_t data_len)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_gap_disconnect(void)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_gatt_send_data(const uint8_t *p_data, uint16_t len)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_timer_create(void **p_timer_id, uint32_t timeout_value_ms, tuya_ble_timer_mode mode, tuya_ble_timer_handler_t timeout_handler)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_timer_delete(void *timer_id)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_timer_start(void *timer_id)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_timer_restart(void *timer_id, uint32_t timeout_value_ms)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_timer_stop(void *timer_id)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK void tuya_ble_device_delay_ms(uint32_t ms)
{
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK void tuya_ble_device_delay_us(uint32_t us)
{
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_rand_generator(uint8_t *p_buf, uint8_t len)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_device_reset(void)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_gap_addr_get(tuya_ble_gap_addr_t *p_addr)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_gap_addr_set(tuya_ble_gap_addr_t *p_addr)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_rtc_get_timestamp(uint32_t *timestamp, int32_t *timezone)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_rtc_set_timestamp(uint32_t timestamp, int32_t timezone)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_nv_init(void)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_nv_erase(uint32_t addr, uint32_t size)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_nv_write(uint32_t addr, const uint8_t *p_data, uint32_t size)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_nv_read(uint32_t addr, uint8_t *p_data, uint32_t size)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_common_uart_init(void)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_common_uart_send_data(const uint8_t *p_data, uint16_t len)
{
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_task_create(void **pp_handle, const char *p_name, void (*p_routine)(void *), void *p_param, uint16_t stack_size, uint16_t priority)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_task_delete(void *p_handle)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_task_suspend(void *p_handle)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_task_resume(void *p_handle)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_msg_queue_create(void **pp_handle, uint32_t msg_num, uint32_t msg_size)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_msg_queue_delete(void *p_handle)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_msg_queue_peek(void *p_handle, uint32_t *p_msg_num)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_msg_queue_send(void *p_handle, void *p_msg, uint32_t wait_ms)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_os_msg_queue_recv(void *p_handle, void *p_msg, uint32_t wait_ms)
{
return true;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK bool tuya_ble_event_queue_send_port(tuya_ble_evt_param_t *evt, uint32_t wait_ms)
{
return true;
}
/**
* @brief 128 bit AES ECB encryption on speicified plaintext and keys
* @param input specifed plain text to be encypted
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @param key keys to encrypt the plaintext
* @param output output buffer to store encrypted data
* @return encryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
__TUYA_BLE_WEAK bool tuya_ble_aes128_ecb_encrypt(uint8_t *key, uint8_t *input, uint16_t input_len, uint8_t *output)
{
return true;
}
/**
* @brief 128 bit AES ECB decryption on speicified encrypted data and keys
* @param input specifed encypted data to be decypted
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @param key keys to decrypt the data
* @param output output buffer to store plain data
* @return decryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
__TUYA_BLE_WEAK bool tuya_ble_aes128_ecb_decrypt(uint8_t *key, uint8_t *input, uint16_t input_len, uint8_t *output)
{
return true;
}
/**
* @brief 128 bit AES CBC encryption on speicified plaintext and keys
* @param input specifed plain text to be encypted
* @param key keys to encrypt the plaintext
* @param output output buffer to store encrypted data
* @param iv initialization vector (IV) for CBC mode
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @return encryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
__TUYA_BLE_WEAK bool tuya_ble_aes128_cbc_encrypt(uint8_t *key, uint8_t *iv, uint8_t *input, uint16_t input_len, uint8_t *output)
{
return true;
}
/**
* @brief 128 bit AES CBC descryption on speicified plaintext and keys
* @param input specifed encypted data to be decypted
* @param key keys to decrypt the data
* @param output output buffer to store plain data
* @param iv initialization vector (IV) for CBC mode
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @return encryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
__TUYA_BLE_WEAK bool tuya_ble_aes128_cbc_decrypt(uint8_t *key, uint8_t *iv, uint8_t *input, uint16_t input_len, uint8_t *output)
{
return true;
}
/**
* @brief MD5 checksum
* @param input specifed plain text to be encypted
* @param output output buffer to store md5 result data,output data len is always 16
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
__TUYA_BLE_WEAK bool tuya_ble_md5_crypt(uint8_t *input, uint16_t input_len, uint8_t *output)
{
return true;
}
/**
* @brief SHA256 checksum
* @param input specifed plain text to be encypted
* @param output output buffer to store sha256 result data,output data len is always 32
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
__TUYA_BLE_WEAK bool tuya_ble_sha256_crypt(const uint8_t *input, uint16_t input_len, uint8_t *output)
{
return true;
}
/**
*@brief storage private data, for example: token/dev cert/keys
*@param private_data_type describe private data type, see the tuay_ble_private_data_type enum define
*@param p_data storage data point
*@param data_size p_data size
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_storage_private_data(tuya_ble_private_data_type private_data_type, uint8_t *p_data, uint32_t data_size)
{
return 0;
}
/**
*@brief Get device certificate length
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK uint32_t tuya_ble_get_dev_crt_len(void)
{
return 0;
}
/**
*@brief Get device certificate data
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_get_dev_crt_der(uint8_t *p_der, uint32_t der_len)
{
return TUYA_BLE_ERR_NOT_FOUND;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_ecc_keypair_gen_secp256r1(uint8_t *public_key, uint8_t *private_key)
{
return TUYA_BLE_ERR_INVALID_STATE;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_ecc_shared_secret_compute_secp256r1(uint8_t *public_key, uint8_t *private_key, uint8_t *secret_key)
{
return TUYA_BLE_ERR_INVALID_STATE;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_ecc_sign_secp256r1(const uint8_t *p_sk, const uint8_t *p_data, uint32_t data_size, uint8_t *p_sig)
{
return TUYA_BLE_ERR_INVALID_STATE;
}
/**
*@brief
*@param
*
*@note
*
* */
__TUYA_BLE_WEAK tuya_ble_status_t tuya_ble_ecc_verify_secp256r1(const uint8_t *p_pk, const uint8_t *p_data, uint32_t data_size, const uint8_t *p_sig)
{
return TUYA_BLE_ERR_RESOURCES;
}
/**
* @brief This function calculates the full generic HMAC
* on the input buffer with the provided key.
* @param key The HMAC secret key.
* @param key_len The length of the HMAC secret key in Bytes.
* @param input specifed plain text to be encypted
* @param output output buffer to store the result data
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
__TUYA_BLE_WEAK bool tuya_ble_hmac_sha1_crypt(const uint8_t *key, uint32_t key_len, const uint8_t *input, uint32_t input_len, uint8_t *output)
{
return true;
}
/**
* @brief This function calculates the full generic HMAC
* on the input buffer with the provided key.
* @param key The HMAC secret key.
* @param key_len The length of the HMAC secret key in Bytes.
* @param input specifed plain text to be encypted
* @param output output buffer to store the result data
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
__TUYA_BLE_WEAK bool tuya_ble_hmac_sha256_crypt(const uint8_t *key, uint32_t key_len, const uint8_t *input, uint32_t input_len, uint8_t *output)
{
return true;
}
/**
* @brief Allocate a memory block with required size.
*
*
* @param[in] size Required memory size.
*
* @return The address of the allocated memory block. If the address is NULL, the
* memory allocation failed.
*/
__TUYA_BLE_WEAK void *tuya_ble_port_malloc(uint32_t size);
/**
*
* @brief Free a memory block that had been allocated.
*
* @param[in] pv The address of memory block being freed.
*
* @return None.
*/
__TUYA_BLE_WEAK void tuya_ble_port_free(void *pv);

View File

@ -1,710 +0,0 @@
/**
* \file tuya_ble_port.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_PORT_H__
#define TUYA_BLE_PORT_H__
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_config.h"
#include "tuya_ble_port_peripheral.h"
void tuya_ble_device_enter_critical(void);
void tuya_ble_device_exit_critical(void);
#if defined(TUYA_BLE_PORT_PLATFORM_HEADER_FILE)
/**
* @file TUYA_BLE_PORT_PLATFORM_HEADER_FILE
*
* @brief Platform header file
* @note
* Must declare or define 'tuya_ble_device_enter_critical' and 'tuya_ble_device_exit_critical' in the platform header file.
* An example on the nrf52832 platform is as follows
* @example
* @code
#define TUYA_BLE_PORT_PLATFORM_HEADER_FILE "tuya_ble_port_nrf52832.h" ///<in custom_tuya_ble_config.h file.
* @endcode
* Defined in the tuya_ble_port_nrf52832.h file as follows
*
* @code
#define tuya_ble_device_enter_critical() \
{ \
uint8_t __CR_NESTED = 0; \
app_util_critical_region_enter(&__CR_NESTED);
#define tuya_ble_device_exit_critical() \
app_util_critical_region_exit(__CR_NESTED); \
}
* @endcode
*/
#include TUYA_BLE_PORT_PLATFORM_HEADER_FILE
#else
#define TUYA_BLE_PRINTF(...)
#define TUYA_BLE_HEXDUMP(...)
/**@brief Macro for entering and leaving a critical region.
*
* @note Due to implementation details, there must exist one and only one call to
* tuya_ble_device_exit_critical() for each call to tuya_ble_device_enter_critical(), and they must be located
* in the same scope.
*/
//#define tuya_ble_device_enter_critical()
//#define tuya_ble_device_exit_critical()
#endif
tuya_ble_status_t tuya_ble_gap_advertising_adv_data_update(uint8_t const *p_ad_data, uint8_t ad_len);
tuya_ble_status_t tuya_ble_gap_advertising_scan_rsp_data_update(uint8_t const *p_sr_data, uint8_t sr_len);
tuya_ble_status_t tuya_ble_gap_disconnect(void);
tuya_ble_status_t tuya_ble_gatt_send_data(const uint8_t *p_data, uint16_t len);
/**
*@brief Function for update the device information characteristic value.
*@param[in] p_data The pointer to the data to be updated.
*@param[in] data_len The length of the data to be updated.
*
*@note The device information characteristic uuid : 00000003-0000-1001-8001-00805F9B07D0
*
* */
tuya_ble_status_t tuya_ble_device_info_characteristic_value_update(uint8_t const *p_data, uint8_t data_len);
/**
* @brief Create a timer.
* @param [out] p_timer_id: a pointer to timer id address which can uniquely identify the timer.
[in] timeout_value_ms Number of milliseconds to time-out event
* [in] timeout_handler: a pointer to a function which can be
* called when the timer expires.
* [in] mode: repeated or single shot.
* @return TUYA_BLE_SUCCESS If the timer was successfully created.
* TUYA_BLE_ERR_INVALID_PARAM Invalid timer id supplied.
* TUYA_BLE_ERR_INVALID_STATE timer module has not been initialized or the
* timer is running.
* TUYA_BLE_ERR_NO_MEM timer pool is full.
*
* */
tuya_ble_status_t tuya_ble_timer_create(void **p_timer_id, uint32_t timeout_value_ms, tuya_ble_timer_mode mode, tuya_ble_timer_handler_t timeout_handler);
/**
* @brief Delete a timer.
* @param [in] timer_id: timer id
* @return TUYA_BLE_SUCCESS If the timer was successfully deleted.
* TUYA_BLE_ERR_INVALID_PARAM Invalid timer id supplied..
* */
tuya_ble_status_t tuya_ble_timer_delete(void *timer_id);
/**
* @brief Start a timer.
* @param [in] timer_id: timer id
*
* @return TUYA_BLE_SUCCESS If the timer was successfully started.
* TUYA_BLE_ERR_COMMON Invalid timer id supplied.
* @note If the timer has already started, it will start counting again.
* */
tuya_ble_status_t tuya_ble_timer_start(void *timer_id);
/**
* @brief Restart a timer.
* @param [in] timer_id: timer id
* [in] timeout_value_ms: New number of milliseconds to time-out event
* @return TUYA_BLE_SUCCESS If the timer was successfully started.
* TUYA_BLE_ERR_COMMON Invalid timer id supplied.
* @note If the timer has already started, it will start counting again.
* */
tuya_ble_status_t tuya_ble_timer_restart(void *timer_id, uint32_t timeout_value_ms);
/**
* @brief Stop a timer.
* @param [in] timer_id: timer id
* @return TUYA_BLE_SUCCESS If the timer was successfully stopped.
* TUYA_BLE_ERR_INVALID_PARAM Invalid timer id supplied.
*
* */
tuya_ble_status_t tuya_ble_timer_stop(void *timer_id);
/**
* @brief Function for delaying execution for a number of milliseconds.
*
* @param ms_time Number of milliseconds to wait.
*/
void tuya_ble_device_delay_ms(uint32_t ms);
/**
* @brief Function for delaying execution for a number of microseconds.
*
* @param us_time Number of microseconds to wait.
*/
void tuya_ble_device_delay_us(uint32_t us);
/**
* @brief Function for RESET device.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_device_reset(void);
/**
* @brief Function for get mac addr.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_gap_addr_get(tuya_ble_gap_addr_t *p_addr);
/**
* @brief Function for update mac addr.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_gap_addr_set(tuya_ble_gap_addr_t *p_addr);
/**
* @brief Get ture random bytes .
* @param [out] p_buf: pointer to data
* [in] len: Number of bytes to take from pool and place in
* p_buff
* @return TUYA_BLE_SUCCESS The requested bytes were written to
* p_buff
* TUYA_BLE_ERR_NO_MEM No bytes were written to the buffer, because
* there were not enough random bytes available.
* @note SHOULD use TRUE random num generator
* */
tuya_ble_status_t tuya_ble_rand_generator(uint8_t *p_buf, uint8_t len);
/**
* @brief Function for get the unix timestamp.
*
* @note timezone: 100 times the actual time zone
*.
* */
tuya_ble_status_t tuya_ble_rtc_get_timestamp(uint32_t *timestamp, int32_t *timezone);
/**
* @brief Function for set the unix timestamp.
*
* @note timezone: 100 times the actual time zone,Eastern eight zones:8x100
*.
* */
tuya_ble_status_t tuya_ble_rtc_set_timestamp(uint32_t timestamp, int32_t timezone);
/**
* @brief Initialize the NV module.
* @note
* @note
*
* @param
* @param
*
* @return result
*/
tuya_ble_status_t tuya_ble_nv_init(void);
/**
* @brief Erase data on flash.
* @note This operation is irreversible.
* @note This operation's units is different which on many chips.
*
* @param addr flash address
* @param size erase bytes size
*
* @return result
*/
tuya_ble_status_t tuya_ble_nv_erase(uint32_t addr, uint32_t size);
/**
* @brief Write data to flash.
*
* @note This operation must after erase. @see tuya_ble_nv_erase.
*
* @param addr flash address
* @param p_data the write data buffer
* @param size write bytes size
*
* @return result
*/
tuya_ble_status_t tuya_ble_nv_write(uint32_t addr, const uint8_t *p_data, uint32_t size);
/**
* @brief Read data from flash.
* @note
*
* @param addr flash address
* @param buf buffer to store read data
* @param size read bytes size
*
* @return result
*/
tuya_ble_status_t tuya_ble_nv_read(uint32_t addr, uint8_t *p_data, uint32_t size);
/**
* @brief Initialize uart peripheral.
* @note UART_PARITY_NO_PARTY,UART_STOP_BITS_1,UART_WROD_LENGTH_8BIT;
* 9600 baud rate.
* @param No parameter.
*
* @return tuya_ble_status_t
*/
tuya_ble_status_t tuya_ble_common_uart_init(void);
/**
* @brief Send data to uart.
* @note
*
* @param p_data the send data buffer
* @param len to send bytes size
*
* @return result
*/
tuya_ble_status_t tuya_ble_common_uart_send_data(const uint8_t *p_data, uint16_t len);
/**
*
*
* \brief Create a new task and add it to the list of tasks that are ready to run.
*
* \param[out] pp_handle Used to pass back a handle by which the created task
* can be referenced.
*
* \param[in] p_name A descriptive name for the task.
*
* \param[in] p_routine Pointer to task routine function that must be implemented
* to never return.
*
* \param[in] p_param Pointer parameter passed to the task routine function.
*
* \param[in] stack_size The size of the task stack that is specified as the number
* of bytes.
*
* \param[in] priority The priority at which the task should run. Higher priority
* task has higher priority value.
*
* \return The status of the task creation.
* \retval true Task was created successfully and added to task ready list.
* \retval false Task was failed to create.
*/
bool tuya_ble_os_task_create(void **pp_handle, const char *p_name, void (*p_routine)(void *), void *p_param, uint16_t stack_size, uint16_t priority);
/**
*
*
* \brief Remove a task from RTOS's task management. The task being deleted will be removed
* from RUNNING, READY or WAITING state.
*
* \param[in] p_handle The handle of the task to be deleted.
*
* \return The status of the task deletion.
* \retval true Task was deleted successfully.
* \retval false Task was failed to delete.
*/
bool tuya_ble_os_task_delete(void *p_handle);
/**
*
*
* \brief Suspend the task. The suspended task will not be scheduled and never get
* any microcontroller processing time.
*
* \param[in] p_handle The handle of the task to be suspended.
*
* \return The status of the task suspension.
* \retval true Task was suspended successfully.
* \retval false Task was failed to suspend.
*/
bool tuya_ble_os_task_suspend(void *p_handle);
/**
*
*
* \brief Resume the suspended task.
*
* \param[in] p_handle The handle of the task to be resumed.
*
* \return The status of the task resume.
* \retval true Task was resumed successfully.
* \retval false Task was failed to resume.
*/
bool tuya_ble_os_task_resume(void *p_handle);
/**
*
*
* \brief Creates a message queue instance. This allocates the storage required by the
* new queue and passes back a handle for the queue.
*
* \param[out] pp_handle Used to pass back a handle by which the message queue
* can be referenced.
*
* \param[in] msg_num The maximum number of items that the queue can contain.
*
* \param[in] msg_size The number of bytes each item in the queue will require. Items
* are queued by copy, not by reference, so this is the number of
* bytes that will be copied for each posted item. Each item on the
* queue must be the same size.
*
* \return The status of the message queue creation.
* \retval true Message queue was created successfully.
* \retval false Message queue was failed to create.
*/
bool tuya_ble_os_msg_queue_create(void **pp_handle, uint32_t msg_num, uint32_t msg_size) ;
/**
*
*
* \brief Delete the specified message queue, and free all the memory allocated for
* storing of items placed on the queue.
*
* \param[in] p_handle The handle to the message queue being deleted.
*
* \return The status of the message queue deletion.
* \retval true Message queue was deleted successfully.
* \retval false Message queue was failed to delete.
*/
bool tuya_ble_os_msg_queue_delete(void *p_handle);
/**
*
*
* \brief Peek the number of items sent and resided on the message queue.
*
* \param[in] p_handle The handle to the message queue being peeked.
*
* \param[out] p_msg_num Used to pass back the number of items residing on the message queue.
*
* \return The status of the message queue peek.
* \retval true Message queue was peeked successfully.
* \retval false Message queue was failed to peek.
*/
bool tuya_ble_os_msg_queue_peek(void *p_handle, uint32_t *p_msg_num);
/**
*
*
* \brief Send an item to the back of the specified message queue. The item is
* queued by copy, not by reference.
*
* \param[in] p_handle The handle to the message queue on which the item is to be sent.
*
* \param[in] p_msg Pointer to the item that is to be sent on the queue. The referenced
* item rather than pointer itself will be copied on the queue.
*
* \param[in] wait_ms The maximum amount of time in milliseconds that the task should
* block waiting for the item to sent on the queue.
* \arg \c 0 No blocking and return immediately.
* \arg \c 0xFFFFFFFF Block infinitely until the item sent.
* \arg \c others The timeout value in milliseconds.
*
* \return The status of the message item sent.
* \retval true Message item was sent successfully.
* \retval false Message item was failed to send.
*/
bool tuya_ble_os_msg_queue_send(void *p_handle, void *p_msg, uint32_t wait_ms);
/**
*
*
* \brief Receive an item from the specified message queue. The item is received by
* copy rather than by reference, so a buffer of adequate size must be provided.
*
* \param[in] p_handle The handle to the message queue from which the item is to be received.
*
* \param[out] p_msg Pointer to the buffer into which the received item will be copied.
* item rather than pointer itself will be copied on the queue.
*
* \param[in] wait_ms The maximum amount of time in milliseconds that the task should
* block waiting for an item to be received from the queue.
* \arg \c 0 No blocking and return immediately.
* \arg \c 0xFFFFFFFF Block infinitely until the item received.
* \arg \c others The timeout value in milliseconds.
*
* \return The status of the message item received.
* \retval true Message item was received successfully.
* \retval false Message item was failed to receive.
*/
bool tuya_ble_os_msg_queue_recv(void *p_handle, void *p_msg, uint32_t wait_ms);
/*
*
*
* \brief If undefine TUYA_BLE_SELF_BUILT_TASK ,application should provide the task to sdk to process the event.
* SDK will use this port to send event to the task of provided by application.
*
* \param[in] evt the message data point to be send.
*
*
* \param[in] wait_ms The maximum amount of time in milliseconds that the task should
* block waiting for an item to be received from the queue.
* \arg \c 0 No blocking and return immediately.
* \arg \c 0xFFFFFFFF Block infinitely until the item received.
* \arg \c others The timeout value in milliseconds.
*
* \return The status of the message item received.
* \retval true Message item was received successfully.
* \retval false Message item was failed to receive.
* */
bool tuya_ble_event_queue_send_port(tuya_ble_evt_param_t *evt, uint32_t wait_ms);
/**
* @brief 128 bit AES ECB encryption on speicified plaintext and keys
* @param input specifed plain text to be encypted
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @param key keys to encrypt the plaintext
* @param output output buffer to store encrypted data
* @return encryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
bool tuya_ble_aes128_ecb_encrypt(uint8_t *key, uint8_t *input, uint16_t input_len, uint8_t *output);
/**
* @brief 128 bit AES ECB decryption on speicified encrypted data and keys
* @param input specifed encypted data to be decypted
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @param key keys to decrypt the data
* @param output output buffer to store plain data
* @return decryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
bool tuya_ble_aes128_ecb_decrypt(uint8_t *key, uint8_t *input, uint16_t input_len, uint8_t *output);
/**
* @brief 128 bit AES CBC encryption on speicified plaintext and keys
* @param input specifed plain text to be encypted
* @param key keys to encrypt the plaintext
* @param output output buffer to store encrypted data
* @param iv initialization vector (IV) for CBC mode
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @return encryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
bool tuya_ble_aes128_cbc_encrypt(uint8_t *key, uint8_t *iv, uint8_t *input, uint16_t input_len, uint8_t *output);
/**
* @brief 128 bit AES CBC descryption on speicified plaintext and keys
* @param input specifed encypted data to be decypted
* @param key keys to decrypt the data
* @param output output buffer to store plain data
* @param iv initialization vector (IV) for CBC mode
* @param input_len byte length of the data to be descrypted, must be multiples of 16
* @return encryption results
* @retval true successful
* @retval false fail
* @note least significant octet of encrypted data corresponds to encypted[0]
*/
bool tuya_ble_aes128_cbc_decrypt(uint8_t *key, uint8_t *iv, uint8_t *input, uint16_t input_len, uint8_t *output);
/**
* @brief MD5 checksum
* @param input specifed plain text to be encypted
* @param output output buffer to store md5 result data,output data len is always 16
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
bool tuya_ble_md5_crypt(uint8_t *input, uint16_t input_len, uint8_t *output);
/**
* @brief SHA256 checksum
* @param input specifed plain text to be encypted
* @param output output buffer to store sha256 result data,output data len is always 32
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
bool tuya_ble_sha256_crypt(const uint8_t *input, uint16_t input_len, uint8_t *output);
/*
*@brief storage private data, for example: token/dev cert/keys
*@param private_data_type describe data type
*@param p_data storage data point
*@param data_size p_data size
*
*@note
*
* */
tuya_ble_status_t tuya_ble_storage_private_data(tuya_ble_private_data_type private_data_type, uint8_t *p_data, uint32_t data_size);
/*
*@brief Get device certificate length
*@param
*
*@note
*
* */
uint32_t tuya_ble_get_dev_crt_len(void);
/*
*@brief Get device certificate data
*@param
*
*@note
*
* */
tuya_ble_status_t tuya_ble_get_dev_crt_der(uint8_t *p_der, uint32_t der_len);
/*
*@brief
*@param
*
*@note
*
* */
tuya_ble_status_t tuya_ble_ecc_keypair_gen_secp256r1(uint8_t *public_key, uint8_t *private_key);
/*
*@brief
*@param
*
*@note
*
* */
tuya_ble_status_t tuya_ble_ecc_shared_secret_compute_secp256r1(uint8_t *public_key, uint8_t *private_key, uint8_t *secret_key);
/*
*@brief
*@param
*
*@note
*
* */
tuya_ble_status_t tuya_ble_ecc_sign_secp256r1(const uint8_t *p_sk, const uint8_t *p_data, uint32_t data_size, uint8_t *p_sig);
/*
*@brief
*@param
*
*@note
*
* */
tuya_ble_status_t tuya_ble_ecc_verify_secp256r1(const uint8_t *p_pk, const uint8_t *p_hash, uint32_t hash_size, const uint8_t *p_sig);
/**
* @brief This function calculates the full generic HMAC
* on the input buffer with the provided key.
* @param key The HMAC secret key.
* @param key_len The length of the HMAC secret key in Bytes.
* @param input specifed plain text to be encypted
* @param output output buffer to store the result data
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
bool tuya_ble_hmac_sha1_crypt(const uint8_t *key, uint32_t key_len, const uint8_t *input, uint32_t input_len, uint8_t *output);
/**
* @brief This function calculates the full generic HMAC
* on the input buffer with the provided key.
* @param key The HMAC secret key.
* @param key_len The length of the HMAC secret key in Bytes.
* @param input specifed plain text to be encypted
* @param output output buffer to store the result data
* @param input_len byte length of the data to be encypted
* @return encryption results
* @retval true successful
* @retval false fail
* @note
*/
bool tuya_ble_hmac_sha256_crypt(const uint8_t *key, uint32_t key_len, const uint8_t *input, uint32_t input_len, uint8_t *output);
/**
* \brief Allocate a memory block with required size.
*
*
* \param[in] size Required memory size.
*
* \return The address of the allocated memory block. If the address is NULL, the
* memory allocation failed.
*/
void *tuya_ble_port_malloc(uint32_t size);
/**
*
* \brief Free a memory block that had been allocated.
*
* \param[in] pv The address of memory block being freed.
*
* \return None.
*/
void tuya_ble_port_free(void *pv);
#endif

View File

@ -1,32 +0,0 @@
/**
* \file tuya_ble_port_peripheral.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_port.h"
#include "tuya_ble_type.h"

View File

@ -1,43 +0,0 @@
/**
* \file tuya_ble_port_peripheral.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_PORT_PERIPHERAL_H__
#define TUYA_BLE_PORT_PERIPHERAL_H__
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#endif

View File

@ -1,86 +0,0 @@
/**
* \file tuya_ble_stdlib.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_STDLIB_H__
#define TUYA_BLE_STDLIB_H__
/*
* If not using the standard library,please set to 0 . Then implement the library functions required by the TUYA BLE SDK in other files and declare in this file.
*/
#define TUYA_BLE_USE_STDLIB 1
#if TUYA_BLE_USE_STDLIB
#include "cpu.h"
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#else
//
typedef unsigned char uint8_t ;
typedef signed char int8_t;
typedef unsigned short uint16_t;
typedef signed short int16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
#define true 1
#define false 0
..........
void *memset(void *str, int32_t c, uint32_t n);
void *memcpy(void *str1, const void *str2, uint32_t n);
int32_t memcmp(const void *str1, const void *str2, uint32_t n);
uint32_t strlen(const char *str);
int32_t rand(void);
int64_t atoll(const char *str);
.............
#endif
#endif

View File

@ -1,405 +0,0 @@
/**
* \file tuya_ble_api.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_API_H__
#define TUYA_BLE_API_H__
#include "tuya_ble_type.h"
#include "tuya_ble_internal_config.h"
#include "tuya_ble_port.h"
#if (TUYA_BLE_USE_OS==0)
/**
* @brief Function for executing all enqueued tasks.
*
* @note This function must be called from within the main loop. It will
* execute all events scheduled since the last time it was called.
* */
void tuya_ble_main_tasks_exec(void);
#endif
/**
* @brief Function for transmit ble data from peer devices to tuya sdk.
*
* @note This function must be called from where the ble data is received.
*.
* */
tuya_ble_status_t tuya_ble_gatt_receive_data(uint8_t *p_data, uint16_t len);
/**
* @brief Function for transmit uart data to tuya sdk.
*
* @note This function must be called from where the uart data is received.
*.
* */
tuya_ble_status_t tuya_ble_common_uart_receive_data(uint8_t *p_data, uint16_t len);
/**
* @brief Function for send the full instruction received from uart to the sdk.
*
* @param
* [in]p_data : pointer to full instruction data(Complete instruction,include0x55 or 0x66 0xaa and checksum.)
* [in]len : Number of bytes of pdata.
*
* @note If the application uses a custom uart parsing algorithm to obtain the full uart instruction,then call this function to send the full instruction.
*
* */
tuya_ble_status_t tuya_ble_common_uart_send_full_instruction_received(uint8_t *p_data, uint16_t len);
/**
* @brief Function for update the device id to tuya sdk.
*
* @note the following id of the device must be update immediately when changed.
*.
* */
tuya_ble_status_t tuya_ble_device_update_product_id(tuya_ble_product_id_type_t type, uint8_t len, uint8_t *p_buf);
tuya_ble_status_t tuya_ble_device_update_login_key(uint8_t *p_buf, uint8_t len);
#if ((TUYA_BLE_PROTOCOL_VERSION_HIGN==4) && (TUYA_BLE_BEACON_KEY_ENABLE))
tuya_ble_status_t tuya_ble_device_update_beacon_key(uint8_t *p_buf, uint8_t len);
#endif
tuya_ble_status_t tuya_ble_device_update_bound_state(uint8_t state);
tuya_ble_status_t tuya_ble_device_update_mcu_version(uint32_t mcu_firmware_version, uint32_t mcu_hardware_version);
/**
* @brief Function for initialize the tuya sdk.
*
* @note appliction should call this after all platform init complete.
*.
* */
tuya_ble_status_t tuya_ble_sdk_init(tuya_ble_device_param_t *param_data);
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN==4)
/**
* @brief Function for send the dp point data.
*
* @param [in]sn: The sending sequence number of the application definition management.
* [in]type : DP_SEND_TYPE_ACTIVE- The device actively sends dp data;DP_SEND_TYPE_PASSIVE- The device passively sends dp data. For example, in order to answer the dp query command of the mobile app. Currently only applicable to WIFI+BLE combo devices.
* [in]mode : See the description in the 'tuya_ble_type.h' file for details.
* [in]ack : See the description in the 'tuya_ble_type.h' file for details.
* [in]p_dp_data : The pointer of dp data .
* [in]dp_data_len : The length of dp data .
* @note new api, The length of each dp data sent through this function must be 2 bytes. DTLD->'L' must be 2 bytes.
*.
* */
tuya_ble_status_t tuya_ble_dp_data_send(uint32_t sn, tuya_ble_dp_data_send_type_t type, tuya_ble_dp_data_send_mode_t mode, tuya_ble_dp_data_send_ack_t ack, uint8_t *p_dp_data, uint32_t dp_data_len);
/**
* @brief Function for send the dp data with time.
*
* @param [in]sn: The sending sequence number of the application definition management.
* [in]mode : See the description in the 'tuya_ble_type.h' file for details.
* [in]time_type : DP_TIME_TYPE_MS_STRING - Indicates that the following 'p_time_data' is a string of milliseconds that must be 13 bytes in length.
* E.g, 'p_time_data' points to the string "1600777955000";
* DP_TIME_TYPE_UNIX_TIMESTAMP - Indicates that the following 'p_time_data' points to the four-byte unix timestamp data.
* E.g, unix timestamp is 1600777955 = 0x5F69EEE3, then 'p_time_data' is {0x5F,0x69,0xEE,0xE3} ;
* [in]p_time_data : time data pointer.
* [in]p_dp_data : The pointer of dp data .
* [in]dp_data_len : The length of dp data .
* @note new api, The length of each dp data sent through this function must be 2 bytes. DTLD->'L' must be 2 bytes.
*. The default type of this function is 'DP_SEND_TYPE_ACTIVE', and the default ack is 'DP_SEND_WITH_RESPONSE', which cannot be changed.
* */
tuya_ble_status_t tuya_ble_dp_data_with_time_send(uint32_t sn, tuya_ble_dp_data_send_mode_t mode, tuya_ble_dp_data_send_time_type_t time_type, uint8_t *p_time_data, uint8_t *p_dp_data, uint32_t dp_data_len);
#else
/**
* @brief Function for report the dp point data.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_dp_data_report(uint8_t *p_data, uint32_t len);
/**
* @brief Function for report the dp point data with time.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_dp_data_with_time_report(uint32_t timestamp, uint8_t *p_data, uint32_t len);
/**
* @brief Function for report the dp point data with time.
*
* @note time_string: 13-byte millisecond string ,for example ,"0000000123456";
*.
* */
tuya_ble_status_t tuya_ble_dp_data_with_time_ms_string_report(uint8_t *time_string, uint8_t *p_data, uint32_t len);
/**
* @brief Function for report the dp point data with flag.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_dp_data_with_flag_report(uint16_t sn, tuya_ble_dp_data_send_mode_t mode, uint8_t *p_data, uint32_t len);
/**
* @brief Function for report the dp point data with flag and time.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_dp_data_with_flag_and_time_report(uint16_t sn, tuya_ble_dp_data_send_mode_t mode, uint32_t timestamp, uint8_t *p_data, uint32_t len);
/**
* @brief Function for report the dp point data with flag and time.
*
* @note time_string: 13-byte millisecond string ,for example ,"0000000123456";
*.
* */
tuya_ble_status_t tuya_ble_dp_data_with_flag_and_time_ms_string_report(uint16_t sn, tuya_ble_dp_data_send_mode_t mode, uint8_t *time_string, uint8_t *p_data, uint32_t len);
#endif
/**
* @brief Function for process the internal state of tuya sdk, application should call this in connect handler.
*
* @note
*.
* */
void tuya_ble_connected_handler(void);
/**
* @brief Function for process the internal state of tuya sdk, application should call this in disconnect handler.
*
* @note
*.
* */
void tuya_ble_disconnected_handler(void);
#if TUYA_BLE_LINK_LAYER_ENCRYPTION_SUPPORT_ENABLE
/**
*@brief Function for update the link encrypted status to sdk, application should call this function when the link layer encryption is successful.
*@note
*
* */
void tuya_ble_link_encrypted_handler(void);
#endif
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN >= 3)
/**
* @brief Function for process the internal state of tuya sdk, application should call this in disconnect handler.
* @param [in]on_off: 0-off ,1 - on.
* @note
*.
* */
tuya_ble_status_t tuya_ble_adv_data_connecting_request_set(uint8_t on_off);
#endif
/**
* @brief Function for data passthrough.
*
* @note The tuya sdk will forwards the data to the app.
*.
* */
tuya_ble_status_t tuya_ble_data_passthrough(uint8_t *p_data, uint32_t len);
/**
* @brief Function for response the production test instruction asynchronous.
*
* @param [in]channel: 0-uart ,1 - ble.
* [in]pdata : pointer to production test cmd data(Complete instruction,include0x66 0xaa and checksum.)
* [in]len : Number of bytes of pdata.
* @note The tuya sdk will forwards the data to the app.
*.
* */
tuya_ble_status_t tuya_ble_production_test_asynchronous_response(uint8_t channel, uint8_t *p_data, uint32_t len);
/**
* @brief Function for response for the net config req.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_net_config_response(int16_t result_code);
#if (!TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
/**
* @brief Function for response for ubound req.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_ubound_response(uint8_t result_code);
/**
* @brief Function for response for anomaly ubound req.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_anomaly_ubound_response(uint8_t result_code);
/**
* @brief Function for response for device reset req.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_device_reset_response(uint8_t result_code);
#endif
/**
* @brief Function for get the ble connet status.
*
* @note
*.
* */
tuya_ble_connect_status_t tuya_ble_connect_status_get(void);
/**
* @brief Function for notify the sdk the device has unbind.
*
* @note
*.
* */
tuya_ble_status_t tuya_ble_device_unbind(void);
/**
* @brief Function for notify the sdk the device has resumes factory Settings.
*
* @note When the device resumes factory Settings,shoule notify the sdk.
*.
* */
tuya_ble_status_t tuya_ble_device_factory_reset(void);
/**
* @brief Function for Request update time.
*
* @param time_type: 0-13-byte millisecond string [from cloud],1 - normal time format [from cloud] , 2 - normal time format[from app local]
* @note
*.
* */
tuya_ble_status_t tuya_ble_time_req(uint8_t time_type);
/**
* @brief Function for response the ota req.
*
* @note response the ota data req from call back event.
*.
* */
tuya_ble_status_t tuya_ble_ota_response(tuya_ble_ota_response_t *p_data);
/**
* @brief Function for send custom event to main process of ble sdk.
*
* @note
*.
* */
uint8_t tuya_ble_custom_event_send(tuya_ble_custom_evt_t evt);
#if TUYA_BLE_USE_OS
/**
* @brief Function for registe queue to receive call back evt when use os
*
* @note
*
* */
tuya_ble_status_t tuya_ble_callback_queue_register(void *cb_queue);
/**
* @brief Function for response the event.
*
* @note if use os,must be sure to call this function after process one event in queue.
*
* */
tuya_ble_status_t tuya_ble_event_response(tuya_ble_cb_evt_param_t *param);
#else
/**
* @brief Function for registe call back functions.
*
* @note appliction should receive the message from the call back registed by this function.
*
* */
tuya_ble_status_t tuya_ble_callback_queue_register(tuya_ble_callback_t cb);
/**
* @brief Function for get scheduler queue size.
*
* @note If it returns 0, it means that the queue has not been initialized.
*
* */
uint16_t tuya_ble_scheduler_queue_size_get(void);
/**
* @brief Function for get queue free space.
*
* @note
*
* */
uint16_t tuya_ble_scheduler_queue_space_get(void);
/**
* @brief Function for get the number of current events in the queue.
*
* @note
*
* */
uint16_t tuya_ble_scheduler_queue_events_get(void);
#endif
/**
* @brief Function for check if sleep is allowed.
*
* @note If it returns true, it means that sleep is allowed.
*
* */
bool tuya_ble_sleep_allowed_check(void);
#endif

View File

@ -1,92 +0,0 @@
/**
* \file tuya_ble_bulkdata.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_BULK_DATA_H_
#define TUYA_BLE_BULK_DATA_H_
#ifdef __cplusplus
extern "C" {
#endif
/*********************************************************************
* INCLUDE
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
/**@brief Macro for defining bulk data transfer protocol. */
#define FRM_BULK_DATA_READ_INFO_REQ 0x0007 //APP->BLE
#define FRM_BULK_DATA_READ_INFO_RESP 0x0007 //BLE->APP
#define FRM_BULK_DATA_READ_DATA_REQ 0x0008 //APP->BLE
#define FRM_BULK_DATA_READ_DATA_RESP 0x0008 //BLE->APP
#define FRM_BULK_DATA_SEND_DATA 0x0009 //BLE->APP
#define FRM_BULK_DATA_ERASE_DATA_REQ 0x000A //APP->BLE
#define FRM_BULK_DATA_ERASE_DATA_RESP 0x000A //BLE->APP
/**@brief Function for get the block size used for bulk data reading.
*
*
* @param[out] block size used for bulk data reading.
* @note The block size depends on the mtu value negotiated after the BLE connection is established.
* If the return value is 0, stop the current bulk data transmission.
*/
uint32_t tuya_ble_bulk_data_read_block_size_get(void);
/**@brief Function for handling the bulk data request.
*
*
* @param[in] cmd Request command.
* @param[in] p_recv_data Pointer to the buffer with received data.
* @param[in] recv_data_len Length of received data.
*/
void tuya_ble_handle_bulk_data_req(uint16_t cmd, uint8_t *p_recv_data, uint32_t recv_data_len);
/**@brief Function for respond to app requests.
*
*
* @param[in] p_data The pointer to the response data.
*/
tuya_ble_status_t tuya_ble_bulk_data_response(tuya_ble_bulk_data_response_t *p_data);
/**@brief Function for handling the bulk data events.
*
*
* @param[in] p_evt Event received from the application.
*/
void tuya_ble_handle_bulk_data_evt(tuya_ble_evt_param_t *p_evt);
#ifdef __cplusplus
}
#endif
#endif //TUYA_BLE_BULKDATA_H_

View File

@ -1,194 +0,0 @@
/**
* \file tuya_ble_data_handler.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_DATA_HANDLER_H_
#define TUYA_BLE_DATA_HANDLER_H_
#include "tuya_ble_stdlib.h"
#include "tuya_ble_internal_config.h"
#ifdef __cplusplus
extern "C" {
#endif
#define FRM_QRY_DEV_INFO_REQ 0x0000 //APP->BLE
#define FRM_QRY_DEV_INFO_RESP 0x0000 //BLE->APP
#define PAIR_REQ 0x0001 //APP->BLE
#define PAIR_RESP 0x0001 //BLE->APP
#define FRM_CMD_SEND 0x0002 //APP->BLE
#define FRM_CMD_RESP 0x0002 //BLE->APP
#define FRM_STATE_QUERY 0x0003 //APP->BLE
#define FRM_STATE_QUERY_RESP 0x0003 //BLE->APP
#define FRM_LOGIN_KEY_REQ 0x0004 //APP->BLE
#define FRM_LOGIN_KEY_RESP 0x0004 //BLE->APP
#define FRM_UNBONDING_REQ 0x0005 //APP->BLE
#define FRM_UNBONDING_RESP 0x0005 //BLE->APP
#define FRM_DEVICE_RESET 0x0006 //APP->BLE
#define FRM_DEVICE_RESET_RESP 0x0006 //BLE->APP
#define FRM_OTA_START_REQ 0x000C //APP->BLE
#define FRM_OTA_START_RESP 0x000C //BLE->APP
#define FRM_OTA_FILE_INFOR_REQ 0x000D //APP->BLE
#define FRM_OTA_FILE_INFOR_RESP 0x000D //BLE->APP
#define FRM_OTA_FILE_OFFSET_REQ 0x000E //APP->BLE
#define FRM_OTA_FILE_OFFSET_RESP 0x000E //BLE->APP
#define FRM_OTA_DATA_REQ 0x000F //APP->BLE
#define FRM_OTA_DATA_RESP 0x000F //BLE->APP
#define FRM_OTA_END_REQ 0x0010 //APP->BLE
#define FRM_OTA_END_RESP 0x0010 //BLE->APP
#define FRM_FACTORY_TEST_CMD 0x0012 //APP->BLE
#define FRM_FACTORY_TEST_RESP 0x0012 //BLE->APP
#define FRM_ANOMALY_UNBONDING_REQ 0x0014 //APP->BLE
#define FRM_ANOMALY_UNBONDING_RESP 0x0014 //BLE->APP
#define FRM_AUTHENTICATE_PHASE_1_REQ 0x0015 //APP->BLE
#define FRM_AUTHENTICATE_PHASE_1_RESP 0x0015 //BLE->APP
#define FRM_AUTHENTICATE_PHASE_2_REQ 0x0016 //APP->BLE
#define FRM_AUTHENTICATE_PHASE_2_RESP 0x0016 //BLE->APP
#define FRM_AUTHENTICATE_PHASE_3_REQ 0x0017 //APP->BLE
#define FRM_AUTHENTICATE_PHASE_3_RESP 0x0017 //BLE->APP
#define FRM_ANOMALY_UNBONDING_REQ 0x0014 //APP->BLE
#define FRM_ANOMALY_UNBONDING_RESP 0x0014 //BLE->APP
#define FRM_NET_CONFIG_INFO_REQ 0x0021 //APP->BLE
#define FRM_NET_CONFIG_INFO_RESP 0x0021 //BLE->APP
#define FRM_NET_CONFIG_RESPONSE_REPORT_REQ 0x0022 //APP->BLE
#define FRM_NET_CONFIG_RESPONSE_REPORT_RESP 0x0022 //BLE->APP
#define FRM_DATA_PASSTHROUGH_REQ 0x0023 //APP<->BLE
#define FRM_DP_DATA_WRITE_REQ 0x0027 //APP->BLE
#define FRM_DP_DATA_WRITE_RESP 0x0027 //BLE->APP
#define FRM_STAT_REPORT 0x8001 //BLE->APP
#define FRM_STAT_REPORT_RESP 0x8001 //APP->BLE
#define FRM_STAT_WITH_TIME_REPORT 0x8003 //BLE->APP
#define FRM_STAT_WITH_TIME_REPORT_RESP 0x8003 //APP->BLE
#define FRM_DATA_WITH_FLAG_REPORT 0x8004 //BLE->APP
#define FRM_DATA_WITH_FLAG_REPORT_RESP 0x8004 //APP->BLE
#define FRM_DATA_WITH_FLAG_AND_TIME_REPORT 0x8005 //BLE->APP
#define FRM_DATA_WITH_FLAG_AND_TIME_REPORT_RESP 0x8005 //APP->BLE
#define FRM_DP_DATA_SEND_REQ 0x8006 //BLE->APP
#define FRM_DP_DATA_SEND_RESP 0x8006 //APP->BLE
#define FRM_DP_DATA_WITH_TIME_SEND_REQ 0x8007 //BLE->APP
#define FRM_DP_DATA_WITH_TIME_SEND_RESP 0x8007 //APP->BLE
#define FRM_WEATHER_DATA_REQUEST 0x8017 //BLE->APP
#define FRM_WEATHER_DATA_REQUEST_RESP 0x8017 //APP->BLE
#define FRM_WEATHER_DATA_RECEIVED 0x8018 //APP->BLE
#define FRM_WEATHER_DATA_RECEIVED_RESP 0x8018 //BLE->APP
#define FRM_GET_UNIX_TIME_MS_REQ 0x8010 //BLE->APP
#define FRM_GET_UNIX_TIME_MS_RESP 0x8010 //APP->BLE
#define FRM_GET_UNIX_TIME_CHAR_MS_REQ 0x8011 //BLE->APP
#define FRM_GET_UNIX_TIME_CHAR_MS_RESP 0x8011 //APP->BLE
#define FRM_GET_UNIX_TIME_CHAR_DATE_REQ 0x8012 //BLE->APP
#define FRM_GET_UNIX_TIME_CHAR_DATE_RESP 0x8012 //APP->BLE
#define FRM_GET_APP_LOCAL_TIME_REQ 0x8013 //BLE->APP
#define FRM_GET_APP_LOCAL_TIME_RESP 0x8013 //APP->BLE
#define FRM_GET_UNIX_TIME_WITH_DST_REQ 0x8014 //BLE->APP [timestamp + timezone + daylight saving time]
#define FRM_GET_UNIX_TIME_WITH_DST_RESP 0x8014 //APP->BLE [timestamp + timezone + daylight saving time]
typedef enum {
TUYA_BLE_OTA_STATUS_NONE,
TUYA_BLE_OTA_STATUS_START,
TUYA_BLE_OTA_STATUS_FILE_INFO,
TUYA_BLE_OTA_STATUS_FILE_OFFSET,
TUYA_BLE_OTA_STATUS_FILE_DATA,
TUYA_BLE_OTA_STATUS_FILE_END,
TUYA_BLE_OTA_STATUS_MAX,
} tuya_ble_ota_status_t;
typedef struct {
uint32_t send_len;
uint8_t *send_data;
uint32_t encrypt_data_buf_len;
uint8_t *encrypt_data_buf;
} tuya_ble_r_air_send_packet;
typedef struct {
uint32_t recv_len;
uint32_t recv_len_max;
uint8_t *recv_data;
uint32_t decrypt_buf_len;
uint8_t *de_encrypt_buf;
} tuya_ble_r_air_recv_packet;
void tuya_ble_air_recv_packet_free(void);
void tuya_ble_set_device_version(uint32_t firmware_version, uint32_t hardware_version);
void tuya_ble_set_external_mcu_version(uint32_t firmware_version, uint32_t hardware_version);
uint8_t tuya_ble_commData_send(uint16_t cmd, uint32_t ack_sn, uint8_t *data, uint16_t len, uint8_t encryption_mode);
uint8_t tuya_ble_send(uint16_t cmd, uint32_t ack_sn, uint8_t *data, uint16_t len);
void tuya_ble_evt_process(uint16_t cmd, uint8_t *recv_data, uint32_t recv_len);
void tuya_ble_reset_ble_sn(void);
void tuya_ble_commonData_rx_proc(uint8_t *buf, uint16_t len);
void tuya_ble_pair_rand_clear(void);
uint8_t tuya_ble_pair_rand_valid_get(void);
uint32_t tuya_ble_send_packet_data_length_get(void);
void tuya_ble_device_unbond(void);
#if (TUYA_BLE_SECURE_CONNECTION_TYPE==TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY_ADVANCED_ENCRYPTION)
void tuya_ble_auth_data_reset(void);
#endif
#ifdef __cplusplus
}
#endif
#endif // TUYA_BLE_COMMDATA_HANDLER_H_

View File

@ -1,159 +0,0 @@
/**
* \file tuya_ble_event.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_EVENT_H_
#define TUYA_BLE_EVENT_H_
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#ifdef __cplusplus
extern "C" {
#endif
#if (!TUYA_BLE_USE_OS)
#define TUYA_BLE_EVT_MAX_NUM MAX_NUMBER_OF_TUYA_MESSAGE
#define TUYA_BLE_EVT_SIZE 52 //64
enum {
TUYA_BLE_EVT_SEND_SUCCESS = 0,
TUYA_BLE_EVT_SEND_NO_MEMORY = 1,
TUYA_BLE_EVT_SEND_FAIL = 2,
};
#define TUYA_BLE_ERROR_HANDLER(ERR_CODE)
#define TUYA_BLE_ERROR_CHECK(ERR_CODE)
#define TUYA_BLE_ERROR_CHECK_BOOL(BOOLEAN_VALUE)
#define CEIL_DIV(A, B) \
(((A) + (B) - 1) / (B))
/**@brief Compute number of bytes required to hold the scheduler buffer.
*
* @param[in] EVENT_SIZE Maximum size of events to be passed through the scheduler.
* @param[in] QUEUE_SIZE Number of entries in scheduler queue (i.e. the maximum number of events
* that can be scheduled for execution).
*
* @return Required scheduler buffer size (in bytes).
*/
#define TUYA_BLE_SCHED_BUF_SIZE(EVENT_SIZE, QUEUE_SIZE) \
((EVENT_SIZE) * ((QUEUE_SIZE) + 1))
/**@brief Macro for initializing the event scheduler.
*
* @details It will also handle dimensioning and allocation of the memory buffer required by the
* scheduler, making sure the buffer is correctly aligned.
*
* @param[in] EVENT_SIZE Maximum size of events to be passed through the scheduler.
* @param[in] QUEUE_SIZE Number of entries in scheduler queue (i.e. the maximum number of events
* that can be scheduled for execution).
*
* @note Since this macro allocates a buffer, it must only be called once (it is OK to call it
* several times as long as it is from the same location, e.g. to do a reinitialization).
*/
#define TUYA_BLE_SCHED_INIT(EVENT_SIZE, QUEUE_SIZE) \
do \
{ \
static uint32_t TUYA_BLE_SCHED_BUF[CEIL_DIV(TUYA_BLE_SCHED_BUF_SIZE((EVENT_SIZE), (QUEUE_SIZE)), \
sizeof(uint32_t))]; \
uint32_t ERR_CODE = tuya_ble_sched_init((EVENT_SIZE), (QUEUE_SIZE), TUYA_BLE_SCHED_BUF); \
TUYA_BLE_ERROR_CHECK(ERR_CODE); \
} while (0)
/**@brief Function for initializing the Scheduler.
*
* @details It must be called before entering the main loop.
*
* @param[in] max_event_size Maximum size of events to be passed through the scheduler.
* @param[in] queue_size Number of entries in scheduler queue (i.e. the maximum number of
* events that can be scheduled for execution).
* @param[in] p_evt_buffer Pointer to memory buffer for holding the scheduler queue. It must
* be dimensioned using the APP_SCHED_BUFFER_SIZE() macro. The buffer
* must be aligned to a 4 byte boundary.
*
* @note Normally initialization should be done using the TUYA_SCHED_INIT() macro, as that will both
* allocate the scheduler buffer, and also align the buffer correctly.
*
* @retval NRF_SUCCESS Successful initialization.
* @retval NRF_ERROR_INVALID_PARAM Invalid parameter (buffer not aligned to a 4 byte
* boundary).
*/
//uint32_t tuya_ble_sched_init(uint16_t max_event_size, uint16_t queue_size, void * p_evt_buffer);
/**@brief Function for executing all scheduled events.
*
* @details This function must be called from within the main loop. It will execute all events
* scheduled since the last time it was called.
*/
void tuya_sched_execute(void);
/**@brief Function for scheduling an event.
*
* @details Puts an event into the event queue.
*
* @param[in] p_event_data Pointer to event data to be scheduled.
* @param[in] event_size Size of event data to be scheduled.
* @param[in] handler Event handler to receive the event.
*
* @return NRF_SUCCESS on success, otherwise an error code.
*/
//tuya_ble_status_t tuya_ble_sched_event_put(void const * p_event_data, uint16_t event_data_size);
/**@brief Function for getting the current amount of free space in the queue.
*
* @details The real amount of free space may be less if entries are being added from an interrupt.
* To get the sxact value, this function should be called from the critical section.
*
* @return Amount of free space in the queue.
*/
uint16_t tuya_ble_sched_queue_size_get(void);
uint16_t tuya_ble_sched_queue_space_get(void);
uint16_t tuya_ble_sched_queue_events_get(void);
void tuya_ble_event_queue_init(void);
tuya_ble_status_t tuya_ble_message_send(tuya_ble_evt_param_t *evt);
#endif
#ifdef __cplusplus
}
#endif
#endif //

View File

@ -1,221 +0,0 @@
/**
* \file tuya_ble_feature_weather.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_FEATURE_WEATHER_H_
#define TUYA_BLE_FEATURE_WEATHER_H_
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
/**@brief Total number of weather parameters currently supported. */
#define SUPPORT_WEATHER_KEY_TYPE_MAX_NUMS ( 25 )
/**@brief Weather key type. */
typedef enum {
WKT_TEMP = (1 << 0), /**< temperature. */
WKT_THIHG = (1 << 1), /**< high temperature. */
WKT_TLOW = (1 << 2), /**< low temperature. */
WKT_HUMIDITY = (1 << 3), /**< humidity. */
WKT_CONDITION = (1 << 4), /**< weather condition. */
WKT_PRESSURE = (1 << 5), /**< pressure. */
WKT_REALFEEL = (1 << 6), /**< sendible temperature. */
WKT_UVI = (1 << 7), /**< uvi. */
WKT_SUNRISE = (1 << 8), /**< sunrise. */
WKT_SUNSET = (1 << 9), /**< sunset. */
WKT_UNIX = (1 << 10), /**< unix time, Use with sunrise and sunset. */
WKT_LOCAL = (1 << 11), /**< local time, Use with sunrise and sunset. */
WKT_WINDSPEED = (1 << 12), /**< wind speed. */
WKT_WINDDIR = (1 << 13), /**< wind direction. */
WKT_WINDLEVEL = (1 << 14), /**< wind speed scale/level. */
WKT_AQI = (1 << 15), /**< aqi. */
WKT_TIPS = (1 << 16), /**< tips. */
WKT_RANK = (1 << 17), /**< Detailed AQI status and national ranking. */
WKT_PM10 = (1 << 18), /**< pm10. */
WKT_PM25 = (1 << 19), /**< pm2.5. */
WKT_O3 = (1 << 20), /**< o3. */
WKT_NO2 = (1 << 21), /**< no2. */
WKT_CO = (1 << 22), /**< co. */
WKT_SO2 = (1 << 23), /**< so2. */
WKT_CONDITIONNUM = (1 << 24), /**< weather condition mapping id. */
WKT_COMBINE_BITMAP_MAXVAL = (1 << SUPPORT_WEATHER_KEY_TYPE_MAX_NUMS),
} tuya_ble_weather_key_type_t;
/**@brief Weather value type. */
typedef enum {
WVT_INTEGER = 0,
WVT_STRING,
} tuya_ble_weather_value_type_t;
/**@brief Weather location type. */
typedef enum {
WLT_PAIR_NETWORK_LOCATION = 1, /**< Pair network location. */
WLT_APP_CURRENT_LOCATION, /**< Mobile phone current location. */
WLT_CUSTOM_LOCATION, /**< The current sdk version unsupport. */
WLT_MAX,
} tuya_ble_weather_location_type_t;
/**@brief Weather data object structure.
*
*/
typedef struct {
uint8_t n_day; /**< which day. */
tuya_ble_weather_key_type_t key_type; /**< weather key type. */
tuya_ble_weather_value_type_t val_type; /**< weather value type. */
uint8_t value_len; /**< weather value length. */
char vaule[]; /**< weather values. */
} tuya_ble_wd_object_t;
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Function for request weather data. Default request current location of mobile phone
*
* @note Example1: request temperatur & humidity and two days, called: tuya_ble_feature_weather_data_request((WKT_TEMP | WKT_HUMIDITY), 2);
* Example2: request sunrise data&time and ont day, called: tuya_ble_feature_weather_data_request((WKT_SUNRISE | WKT_LOCAL), 1);
* Example3: request highest temperature and seven days, called: tuya_ble_feature_weather_data_request((WKT_THIHG), 7);
* In addition, request sunrise/sunset must be matched with WKT_UNIX/WKT_LOCAL, otherwise the received data is unix time
*
* @param[in] combine_type Request combine types. For details, see the enum of tuya_ble_weather_key_type_t
* @param[in] n_days Request forecast days, rang from [1-7]; 1-means only today, 2-means today+tomorrow ...
*
* @retval TUYA_BLE_ERR_INVALID_PARAM The provided Parameters are not valid.
* @retval TUYA_BLE_ERR_NO_MEM If no memory is available to accept the operation.
* @retval TUYA_BLE_ERR_INTERNAL If weather request message send failed.
* @retval TUYA_BLE_SUCCESS Successful.
*
* */
extern tuya_ble_status_t tuya_ble_feature_weather_data_request(uint32_t combine_type, uint8_t n_days);
/**
* @brief Function for request weather data with appoint location.
*
* @param[in] location_type Request location types. For details, see the enum of tuya_ble_weather_location_type_t.
* @param[in] combine_type Request combine types. For details, see the enum of tuya_ble_weather_key_type_t
* @param[in] n_days Request forecast days, rang from [1-7]; 1-means only today, 2-means today+tomorrow ...
*
* @retval TUYA_BLE_ERR_INVALID_PARAM The provided Parameters are not valid.
* @retval TUYA_BLE_ERR_NO_MEM If no memory is available to accept the operation.
* @retval TUYA_BLE_ERR_INTERNAL If weather request message send failed.
* @retval TUYA_BLE_SUCCESS Successful.
*
* */
extern tuya_ble_status_t tuya_ble_feature_weather_data_request_with_location(tuya_ble_weather_location_type_t location_type, uint32_t combine_type, uint8_t n_days);
/**
* @brief Function for application parse received weather datas, In tuya_cb_handler() function
* add TUYA_BLE_CB_EVT_WEATHER_DATA_REQ_RESPONSE and TUYA_BLE_CB_EVT_WEATHER_DATA_RECEIVED callback
* event and process it. For example:
*
case TUYA_BLE_CB_EVT_WEATHER_DATA_REQ_RESPONSE:
TUYA_APP_LOG_INFO("received weather data request response result code =%d",event->weather_req_response_data.status);
break;
case TUYA_BLE_CB_EVT_WEATHER_DATA_RECEIVED:
tuya_ble_wd_object_t *object;
uint16_t object_len = 0;
for (;;) {
object = (tuya_ble_wd_object_t *)(event->weather_received_data.p_data + object_len);
TUYA_APP_LOG_DEBUG("recvived weather data, n_days=[%d] key=[0x%08x] val_type=[%d] val_len=[%d]", \
object->n_day, object->key_type, object->val_type, object->value_len);
TUYA_APP_LOG_HEXDUMP_DEBUG("vaule :", (uint8_t *)object->vaule, object->value_len);
// TODO .. YOUR JOBS
object_len += (sizeof(tuya_ble_wd_object_t) + object->value_len);
if (object_len >= event->weather_received_data.data_len)
break;
}
break;
* */
/**
* @brief Function for convert weather enum type to string
*
* @note For example input convert type=WKT_TEMP, output key "w.temp"
*
* @param[in] type Convert type
* @param[out] key The ponit of weather key string
*
* @retval TUYA_BLE_ERR_INVALID_PARAM The provided Parameters are not valid.
* @retval TUYA_BLE_ERR_NOT_FOUND No corresponding type was found.
* @retval TUYA_BLE_SUCCESS Successful.
*
* */
extern tuya_ble_status_t tuya_ble_feature_weather_key_enum_type_to_string(tuya_ble_weather_key_type_t type, char *key);
/**
* @brief Function for handler weather data request event
*
* @details Internal use of tuya ble sdk
*
* @param[in] evt For details, see the struct of tuya_ble_evt_param_t
*
* */
extern void tuya_ble_handle_weather_data_request_evt(tuya_ble_evt_param_t *evt);
/**
* @brief Function for handler weather data request response/ack
*
* @details Internal use of tuya ble sdk
*
* @param[in] recv_data The point of recvived response data
* @param[in] recv_len The numbers of data
*
* */
extern void tuya_ble_handle_weather_data_request_response(uint8_t *recv_data, uint16_t recv_len);
/**
* @brief Function for handler weather data received
*
* @details Internal use of tuya ble sdk
*
* @param[in] recv_data The point of recvived weather data
* @param[in] recv_len The numbers of data
*
* */
extern void tuya_ble_handle_weather_data_received(uint8_t *recv_data, uint16_t recv_len);
#ifdef __cplusplus
}
#endif
#endif /* TUYA_BLE_FEATURE_WEATHER_H_ */

View File

@ -1,49 +0,0 @@
/**
* \file tuya_ble_gatt_send_queue.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_GATT_SEND_QUEUE_H_
#define TUYA_BLE_GATT_SEND_QUEUE_H_
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_queue.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
uint8_t *buf;
uint8_t size;
} tuya_ble_gatt_send_data_t;
void tuya_ble_gatt_send_queue_init(void);
void tuya_ble_gatt_send_data_handle(void *evt);
tuya_ble_status_t tuya_ble_gatt_send_data_enqueue(uint8_t *p_data, uint8_t data_len);
#ifdef __cplusplus
}
#endif
#endif //TUYA_BLE_GATT_SEND_QUEUE_H_

View File

@ -1,114 +0,0 @@
/*
* FreeRTOS Kernel V10.0.0
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software. If you wish to use our Amazon
* FreeRTOS name, please do so in a fair use way that does not cause confusion.
*
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
#ifndef TUYA_HEAP_H__
#define TUYA_HEAP_H__
#include "tuya_ble_stdlib.h"
#ifdef __cplusplus
extern "C" {
#endif
#if (TUYA_BLE_USE_PLATFORM_MEMORY_HEAP==0)
#define portBYTE_ALIGNMENT 4
#if portBYTE_ALIGNMENT == 32
#define portBYTE_ALIGNMENT_MASK ( 0x001f )
#endif
#if portBYTE_ALIGNMENT == 16
#define portBYTE_ALIGNMENT_MASK ( 0x000f )
#endif
#if portBYTE_ALIGNMENT == 8
#define portBYTE_ALIGNMENT_MASK ( 0x0007 )
#endif
#if portBYTE_ALIGNMENT == 4
#define portBYTE_ALIGNMENT_MASK ( 0x0003 )
#endif
#if portBYTE_ALIGNMENT == 2
#define portBYTE_ALIGNMENT_MASK ( 0x0001 )
#endif
#if portBYTE_ALIGNMENT == 1
#define portBYTE_ALIGNMENT_MASK ( 0x0000 )
#endif
#ifndef portBYTE_ALIGNMENT_MASK
#error "Invalid portBYTE_ALIGNMENT definition"
#endif
#ifndef tuyaASSERT
#define tuyaASSERT( x )
#define tuyaASSERT_DEFINED 0
#else
#define tuyaASSERT_DEFINED 1
#endif
#ifndef tuyaCOVERAGE_TEST_MARKER
#define tuyaCOVERAGE_TEST_MARKER()
#endif
#ifndef tuya_traceMALLOC
#define tuya_traceMALLOC( pvAddress, uiSize )
#endif
#ifndef tuya_traceFREE
#define tuya_traceFREE( pvAddress, uiSize )
#endif
void *pvTuyaPortMalloc(uint32_t xWantedSize);
void vTuyaPortFree(void *pv);
uint32_t xTuyaPortGetFreeHeapSize(void);
uint32_t xTuyaPortGetMinimumEverFreeHeapSize(void);
#endif
#ifdef __cplusplus
}
#endif
#endif //TUYA_HEAP_H__
/** @} */

View File

@ -1,150 +0,0 @@
/**
* \file tuya_ble_internal_config.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_INTERNAL_CONFIG_H__
#define TUYA_BLE_INTERNAL_CONFIG_H__
#include "tuya_ble_config.h"
#include "tuya_ble_port.h"
#define MAX_NUMBER_OF_TUYA_MESSAGE 16 //!< tuya ble message queue size
//BLE Communication protocol version v4.2
#define TUYA_BLE_PROTOCOL_VERSION_HIGN 0x04
#define TUYA_BLE_PROTOCOL_VERSION_LOW 0x02
#define TUYA_BLE_DP_WRITE_CURRENT_VERSION 0
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN>=4)
#define TUYA_BLE_AIR_FRAME_MAX 1536
#define TUYA_UART_RECEIVE_MAX_DP_DATA_LEN (512+4)
#define TUYA_UART_RECEIVE_MAX_DP_BUFFER_DATA_LEN (512+4)
#define TUYA_BLE_RECEIVE_MAX_DP_DATA_LEN (512+4)
#define TUYA_BLE_SEND_MAX_DP_DATA_LEN TUYA_BLE_RECEIVE_MAX_DP_DATA_LEN
#define TUYA_BLE_SEND_MAX_DATA_LEN (((TUYA_BLE_AIR_FRAME_MAX-17)/16)*16-14)
#define TUYA_BLE_RECEIVE_MAX_DATA_LEN TUYA_BLE_SEND_MAX_DATA_LEN
#else
#define TUYA_BLE_ADVANCED_ENCRYPTION_DEVICE 0
#define TUYA_BLE_AIR_FRAME_MAX 1024
#define TUYA_UART_RECEIVE_MAX_DP_DATA_LEN (255+4)
#define TUYA_UART_RECEIVE_MAX_DP_BUFFER_DATA_LEN (255+4)
#define TUYA_BLE_RECEIVE_MAX_DP_DATA_LEN (255+3)
#define TUYA_BLE_SEND_MAX_DP_DATA_LEN TUYA_BLE_RECEIVE_MAX_DP_DATA_LEN
#define TUYA_BLE_REPORT_MAX_DP_DATA_LEN TUYA_BLE_RECEIVE_MAX_DP_DATA_LEN
#define TUYA_BLE_TRANSMISSION_MAX_DATA_LEN (TUYA_BLE_AIR_FRAME_MAX-29)
#define TUYA_BLE_SEND_MAX_DATA_LEN TUYA_BLE_TRANSMISSION_MAX_DATA_LEN
#define TUYA_BLE_RECEIVE_MAX_DATA_LEN TUYA_BLE_SEND_MAX_DATA_LEN
#endif
#define TUYA_BLE_GATT_SEND_DATA_QUEUE_SIZE (MAX_NUMBER_OF_TUYA_MESSAGE*3)
#if (TUYA_BLE_USE_PLATFORM_MEMORY_HEAP==0)
/**
* MACRO for memory management
*/
#define TUYA_BLE_TOTAL_HEAP_SIZE 5120
#if (TUYA_BLE_TOTAL_HEAP_SIZE<5120)
#define TUYA_BLE_BULK_DATA_MAX_READ_BLOCK_SIZE 512
#else
#define TUYA_BLE_BULK_DATA_MAX_READ_BLOCK_SIZE 1024
#endif
#else
#define TUYA_BLE_BULK_DATA_MAX_READ_BLOCK_SIZE 512
#endif
#ifndef TUYA_BLE_MAX_CALLBACKS
#define TUYA_BLE_MAX_CALLBACKS 1
#endif
#define TUYA_BLE_AUTH_FLASH_ADDR (TUYA_NV_START_ADDR)
#define TUYA_BLE_AUTH_FLASH_BACKUP_ADDR (TUYA_NV_START_ADDR+TUYA_NV_ERASE_MIN_SIZE)
#define TUYA_BLE_SYS_FLASH_ADDR (TUYA_NV_START_ADDR+TUYA_NV_ERASE_MIN_SIZE*2)
#define TUYA_BLE_SYS_FLASH_BACKUP_ADDR (TUYA_NV_START_ADDR+TUYA_NV_ERASE_MIN_SIZE*3)
/**
* 1 - device register from ble 0 - from others
* @note:
*/
#define TUYA_BLE_DEVICE_REGISTER_FROM_BLE (TUYA_BLE_DEVICE_COMMUNICATION_ABILITY&TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_REGISTER_FROM_BLE)
#define TUYA_BLE_DEVICE_AUTH_DATA_STORE TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT
/**
* if 1 ,tuya ble sdk authorization storage into extern medium, For example security chip
*/
#define TUYA_BLE_DEVICE_AUTH_DATA_STORE_EXT_MEDIUM 0
/**
* if 1 ,used ble dongle for product test, the transmit datas will encryption
*/
#define TUYA_BLE_PROD_TEST_SUPPORT_ENCRYPTION 0
/**
* if >=1, the product support oem, when execute prod test will write in pid and json config file
*
* Noticed!!! if enable the macro, need to realization 'tuya_ble_status_t tuya_ble_prod_storage_oem_info(uint8_t *para,uint16_t len)'
* function yourself at the custom_app_product_test.c
*/
#define TUYA_BLE_PROD_SUPPORT_OEM_TYPE TUYA_BLE_PROD_OEM_TYPE_NONE
#if (TUYA_BLE_SYS_FLASH_BACKUP_ADDR>=(TUYA_NV_AREA_SIZE+TUYA_NV_START_ADDR))
#error "Storage Memory overflow!"
#endif
#endif

View File

@ -1,142 +0,0 @@
/**
* \file tuya_ble_log.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_LOG_H__
#define TUYA_BLE_LOG_H__
#include "tuya_ble_stdlib.h"
#include "tuya_ble_internal_config.h"
#include "tuya_ble_log_internal.h"
#if TUYA_BLE_LOG_ENABLE
#ifndef TUYA_BLE_LOG_LEVEL
#define TUYA_BLE_LOG_LEVEL TUYA_BLE_LOG_LEVEL_DEBUG
#endif
#ifndef TUYA_BLE_LOG_COLORS_ENABLE
#define TUYA_BLE_LOG_COLORS_ENABLE 0
#endif
#define TUYA_BLE_LOG_ERROR(...) TUYA_BLE_LOG_INTERNAL_ERROR(__VA_ARGS__)
#define TUYA_BLE_LOG_WARNING(...) TUYA_BLE_LOG_INTERNAL_WARNING( __VA_ARGS__)
#define TUYA_BLE_LOG_INFO(...) TUYA_BLE_LOG_INTERNAL_INFO( __VA_ARGS__)
#define TUYA_BLE_LOG_DEBUG(...) TUYA_BLE_LOG_INTERNAL_DEBUG( __VA_ARGS__)
#define TUYA_BLE_LOG_HEXDUMP_ERROR(...) TUYA_BLE_LOG_INTERNAL_HEXDUMP_ERROR(__VA_ARGS__)
#define TUYA_BLE_LOG_HEXDUMP_WARNING(...) TUYA_BLE_LOG_INTERNAL_HEXDUMP_WARNING( __VA_ARGS__)
#define TUYA_BLE_LOG_HEXDUMP_INFO(...) TUYA_BLE_LOG_INTERNAL_HEXDUMP_INFO( __VA_ARGS__)
#define TUYA_BLE_LOG_HEXDUMP_DEBUG(...) TUYA_BLE_LOG_INTERNAL_HEXDUMP_DEBUG( __VA_ARGS__)
#else
#define TUYA_BLE_LOG_ERROR(...)
#define TUYA_BLE_LOG_WARNING(...)
#define TUYA_BLE_LOG_INFO(...)
#define TUYA_BLE_LOG_DEBUG(...)
#define TUYA_BLE_LOG_HEXDUMP_ERROR(...)
#define TUYA_BLE_LOG_HEXDUMP_WARNING(...)
#define TUYA_BLE_LOG_HEXDUMP_INFO(...)
#define TUYA_BLE_LOG_HEXDUMP_DEBUG(...)
#endif //
#if TUYA_APP_LOG_ENABLE
#ifndef TUYA_APP_LOG_LEVEL
#define TUYA_APP_LOG_LEVEL TUYA_APP_LOG_LEVEL_DEBUG
#endif
#ifndef TUYA_APP_LOG_COLORS_ENABLE
#define TUYA_APP_LOG_COLORS_ENABLE 0
#endif
#define TUYA_APP_LOG_ERROR(...) TUYA_APP_LOG_INTERNAL_ERROR(__VA_ARGS__)
#define TUYA_APP_LOG_WARNING(...) TUYA_APP_LOG_INTERNAL_WARNING( __VA_ARGS__)
#define TUYA_APP_LOG_INFO(...) TUYA_APP_LOG_INTERNAL_INFO( __VA_ARGS__)
#define TUYA_APP_LOG_DEBUG(...) TUYA_APP_LOG_INTERNAL_DEBUG( __VA_ARGS__)
#define TUYA_APP_LOG_HEXDUMP_ERROR(...) TUYA_APP_LOG_INTERNAL_HEXDUMP_ERROR(__VA_ARGS__)
#define TUYA_APP_LOG_HEXDUMP_WARNING(...) TUYA_APP_LOG_INTERNAL_HEXDUMP_WARNING( __VA_ARGS__)
#define TUYA_APP_LOG_HEXDUMP_INFO(...) TUYA_APP_LOG_INTERNAL_HEXDUMP_INFO( __VA_ARGS__)
#define TUYA_APP_LOG_HEXDUMP_DEBUG(...) TUYA_APP_LOG_INTERNAL_HEXDUMP_DEBUG( __VA_ARGS__)
#else
#define TUYA_APP_LOG_ERROR(...)
#define TUYA_APP_LOG_WARNING(...)
#define TUYA_APP_LOG_INFO(...)
#define TUYA_APP_LOG_DEBUG(...)
#define TUYA_APP_LOG_HEXDUMP_ERROR(...)
#define TUYA_APP_LOG_HEXDUMP_WARNING(...)
#define TUYA_APP_LOG_HEXDUMP_INFO(...)
#define TUYA_APP_LOG_HEXDUMP_DEBUG(...)
#endif //
#ifdef TUYA_BLE_ASSERT
#define TUYA_BLE_ERR_HANDLER(ERR_CODE) \
do \
{ \
TUYA_BLE_LOG_ERROR("Error code 0x%04X <%d>. %s:%d\n", ERR_CODE, ERR_CODE, (uint32_t)__FILE__, __LINE__); \
} while (0)
#define TUYA_BLE_ERR_CHECK(ERR_CODE) \
do \
{ \
const uint32_t LOCAL_ERR_CODE = (ERR_CODE); \
if (LOCAL_ERR_CODE != 0) \
{ \
TUYA_BLE_ERR_HANDLER(LOCAL_ERR_CODE); \
} \
} while (0)
#define TUYA_BLE_ERR_TEST(ERR_CODE, EXPECT) \
do \
{ \
const uint32_t LOCAL_ERR_CODE = (ERR_CODE); \
if (LOCAL_ERR_CODE != (EXPECT)) \
{ \
TUYA_BLE_ERR_HANDLER(LOCAL_ERR_CODE); \
} \
} while (0)
#else //
#define TUYA_BLE_ERR_CHECK(ERR_CODE)
#define TUYA_BLE_ERR_TEST(ERR_CODE, EXPECT)
#endif //
#endif // TUYA_BLE_LOG_H__

View File

@ -1,288 +0,0 @@
/**
* \file tuya_ble_log_internal.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_LOG_INTERNAL__H__
#define TUYA_BLE_LOG_INTERNAL__H__
#include "tuya_ble_port.h"
#include "tuya_ble_internal_config.h"
#if !defined(TUYA_BLE_PRINTF)
#error "Not defined printf function."
#elif !defined(TUYA_BLE_HEXDUMP)
#error "Not defined hexdump function."
#endif
#ifndef TUYA_BLE_LOG_COLORS_ENABLE
#define TUYA_BLE_LOG_COLORS_ENABLE 0
#endif
#ifndef TUYA_BLE_LOG_MODULE_NAME
#define TUYA_BLE_LOG_MODULE_NAME "TUYA_BLE"
#endif
#if TUYA_BLE_LOG_COLORS_ENABLE
#define TUYA_BLE_LOG_COLOR_DEFAULT "\x1B[0m"
#define TUYA_BLE_LOG_COLOR_BLACK "\x1B[1;30m"
#define TUYA_BLE_LOG_COLOR_RED "\x1B[1;31m"
#define TUYA_BLE_LOG_COLOR_GREEN "\x1B[1;32m"
#define TUYA_BLE_LOG_COLOR_YELLOW "\x1B[1;33m"
#define TUYA_BLE_LOG_COLOR_BLUE "\x1B[1;34m"
#define TUYA_BLE_LOG_COLOR_MAGENTA "\x1B[1;35m"
#define TUYA_BLE_LOG_COLOR_CYAN "\x1B[1;36m"
#define TUYA_BLE_LOG_COLOR_WHITE "\x1B[1;37m"
#else
#define TUYA_BLE_LOG_COLOR_DEFAULT
#define TUYA_BLE_LOG_COLOR_BLACK
#define TUYA_BLE_LOG_COLOR_RED
#define TUYA_BLE_LOG_COLOR_GREEN
#define TUYA_BLE_LOG_COLOR_YELLOW
#define TUYA_BLE_LOG_COLOR_BLUE
#define TUYA_BLE_LOG_COLOR_MAGENTA
#define TUYA_BLE_LOG_COLOR_CYAN
#define TUYA_BLE_LOG_COLOR_WHITE
#endif
#define TUYA_BLE_LOG_ERROR_COLOR TUYA_BLE_LOG_COLOR_RED
#define TUYA_BLE_LOG_WARNING_COLOR TUYA_BLE_LOG_COLOR_YELLOW
#define TUYA_BLE_LOG_INFO_COLOR TUYA_BLE_LOG_COLOR_DEFAULT
#define TUYA_BLE_LOG_DEBUG_COLOR TUYA_BLE_LOG_COLOR_GREEN
#define TUYA_BLE_LOG_DEFAULT_COLOR TUYA_BLE_LOG_COLOR_DEFAULT
#define TUYA_BLE_LOG_BREAK ": "
//#define TUYA_BLE_LOG_CRLF "\r\n"
#define TUYA_BLE_LOG_CRLF ""
#define TUYA_BLE_ERROR_PREFIX TUYA_BLE_LOG_ERROR_COLOR "[E] " TUYA_BLE_LOG_MODULE_NAME TUYA_BLE_LOG_BREAK
#define TUYA_BLE_WARNING_PREFIX TUYA_BLE_LOG_WARNING_COLOR "[W] " TUYA_BLE_LOG_MODULE_NAME TUYA_BLE_LOG_BREAK
#define TUYA_BLE_INFO_PREFIX TUYA_BLE_LOG_INFO_COLOR "[I] " TUYA_BLE_LOG_MODULE_NAME TUYA_BLE_LOG_BREAK
#define TUYA_BLE_DEBUG_PREFIX TUYA_BLE_LOG_DEBUG_COLOR "[D] " TUYA_BLE_LOG_MODULE_NAME TUYA_BLE_LOG_BREAK
#define TUYA_BLE_LOG_INTERNAL_ERROR(_fmt_, ...) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_ERROR) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_ERROR_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR TUYA_BLE_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_BLE_LOG_INTERNAL_WARNING(_fmt_, ...) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_WARNING) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_WARNING_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR TUYA_BLE_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_BLE_LOG_INTERNAL_INFO(_fmt_, ...) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_INFO) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_INFO_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR TUYA_BLE_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_BLE_LOG_INTERNAL_DEBUG(_fmt_, ...) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_DEBUG) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_DEBUG_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR TUYA_BLE_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_BLE_LOG_INTERNAL_HEXDUMP_ERROR(_fmt_, p_data, len) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_ERROR) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_ERROR_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_BLE_LOG_CRLF,len ); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_BLE_LOG_CRLF); \
} \
} while(0)
#define TUYA_BLE_LOG_INTERNAL_HEXDUMP_WARNING(_fmt_, p_data, len) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_WARNING) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_WARNING_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_BLE_LOG_CRLF,len); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_BLE_LOG_CRLF); \
} \
} while(0)
#define TUYA_BLE_LOG_INTERNAL_HEXDUMP_INFO(_fmt_, p_data, len) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_INFO) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_INFO_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_BLE_LOG_CRLF,len); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_BLE_LOG_CRLF); \
} \
} while(0)
#define TUYA_BLE_LOG_INTERNAL_HEXDUMP_DEBUG(_fmt_, p_data, len) \
do { \
if (TUYA_BLE_LOG_LEVEL >= TUYA_BLE_LOG_LEVEL_DEBUG) \
{ \
TUYA_BLE_PRINTF(TUYA_BLE_DEBUG_PREFIX _fmt_ TUYA_BLE_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_BLE_LOG_CRLF,len); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_BLE_LOG_CRLF); \
} \
} while(0)
/* TUYA APP LOG */
#ifndef TUYA_APP_LOG_COLORS_ENABLE
#define TUYA_APP_LOG_COLORS_ENABLE 0
#endif
#ifndef TUYA_APP_LOG_MODULE_NAME
#define TUYA_APP_LOG_MODULE_NAME "TUYA_APP"
#endif
#if TUYA_APP_LOG_COLORS_ENABLE
#define TUYA_APP_LOG_COLOR_DEFAULT "\x1B[0m"
#define TUYA_APP_LOG_COLOR_BLACK "\x1B[1;30m"
#define TUYA_APP_LOG_COLOR_RED "\x1B[1;31m"
#define TUYA_APP_LOG_COLOR_GREEN "\x1B[1;32m"
#define TUYA_APP_LOG_COLOR_YELLOW "\x1B[1;33m"
#define TUYA_APP_LOG_COLOR_BLUE "\x1B[1;34m"
#define TUYA_APP_LOG_COLOR_MAGENTA "\x1B[1;35m"
#define TUYA_APP_LOG_COLOR_CYAN "\x1B[1;36m"
#define TUYA_APP_LOG_COLOR_WHITE "\x1B[1;37m"
#else
#define TUYA_APP_LOG_COLOR_DEFAULT
#define TUYA_APP_LOG_COLOR_BLACK
#define TUYA_APP_LOG_COLOR_RED
#define TUYA_APP_LOG_COLOR_GREEN
#define TUYA_APP_LOG_COLOR_YELLOW
#define TUYA_APP_LOG_COLOR_BLUE
#define TUYA_APP_LOG_COLOR_MAGENTA
#define TUYA_APP_LOG_COLOR_CYAN
#define TUYA_APP_LOG_COLOR_WHITE
#endif
#define TUYA_APP_LOG_ERROR_COLOR TUYA_APP_LOG_COLOR_RED
#define TUYA_APP_LOG_WARNING_COLOR TUYA_APP_LOG_COLOR_YELLOW
#define TUYA_APP_LOG_INFO_COLOR TUYA_APP_LOG_COLOR_DEFAULT
#define TUYA_APP_LOG_DEBUG_COLOR TUYA_APP_LOG_COLOR_GREEN
#define TUYA_APP_LOG_DEFAULT_COLOR TUYA_APP_LOG_COLOR_DEFAULT
#define TUYA_APP_LOG_BREAK ": "
//#define TUYA_APP_LOG_CRLF "\r\n"
#define TUYA_APP_LOG_CRLF ""
#define TUYA_APP_ERROR_PREFIX TUYA_APP_LOG_ERROR_COLOR "[E] " TUYA_APP_LOG_MODULE_NAME TUYA_APP_LOG_BREAK
#define TUYA_APP_WARNING_PREFIX TUYA_APP_LOG_WARNING_COLOR "[W] " TUYA_APP_LOG_MODULE_NAME TUYA_APP_LOG_BREAK
#define TUYA_APP_INFO_PREFIX TUYA_APP_LOG_INFO_COLOR "[I] " TUYA_APP_LOG_MODULE_NAME TUYA_APP_LOG_BREAK
#define TUYA_APP_DEBUG_PREFIX TUYA_APP_LOG_DEBUG_COLOR "[D] " TUYA_APP_LOG_MODULE_NAME TUYA_APP_LOG_BREAK
#define TUYA_APP_LOG_INTERNAL_ERROR(_fmt_, ...) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_ERROR) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_ERROR_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR TUYA_APP_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_APP_LOG_INTERNAL_WARNING(_fmt_, ...) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_WARNING) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_WARNING_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR TUYA_APP_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_APP_LOG_INTERNAL_INFO(_fmt_, ...) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_INFO) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_INFO_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR TUYA_APP_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_APP_LOG_INTERNAL_DEBUG(_fmt_, ...) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_DEBUG) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_DEBUG_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR TUYA_APP_LOG_CRLF, ##__VA_ARGS__); \
} \
} while(0)
#define TUYA_APP_LOG_INTERNAL_HEXDUMP_ERROR(_fmt_, p_data, len) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_ERROR) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_ERROR_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_APP_LOG_CRLF,len ); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_APP_LOG_CRLF); \
} \
} while(0)
#define TUYA_APP_LOG_INTERNAL_HEXDUMP_WARNING(_fmt_, p_data, len) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_WARNING) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_WARNING_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_APP_LOG_CRLF,len); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_APP_LOG_CRLF); \
} \
} while(0)
#define TUYA_APP_LOG_INTERNAL_HEXDUMP_INFO(_fmt_, p_data, len) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_INFO) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_INFO_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_APP_LOG_CRLF,len); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_APP_LOG_CRLF); \
} \
} while(0)
#define TUYA_APP_LOG_INTERNAL_HEXDUMP_DEBUG(_fmt_, p_data, len) \
do { \
if (TUYA_APP_LOG_LEVEL >= TUYA_APP_LOG_LEVEL_DEBUG) \
{ \
TUYA_BLE_PRINTF(TUYA_APP_DEBUG_PREFIX _fmt_ TUYA_APP_LOG_DEFAULT_COLOR " [len=%d] :" TUYA_APP_LOG_CRLF,len); \
TUYA_BLE_HEXDUMP(p_data, len); \
TUYA_BLE_PRINTF(TUYA_APP_LOG_CRLF); \
} \
} while(0)
#endif // TUYA_BLE_LOG_INTERNAL__H__

View File

@ -1,78 +0,0 @@
/**
* \file tuya_ble_main.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_MAIN_H__
#define TUYA_BLE_MAIN_H__
#include "tuya_ble_type.h"
#include "tuya_ble_internal_config.h"
#ifdef __cplusplus
extern "C" {
#endif
extern tuya_ble_parameters_settings_t tuya_ble_current_para;
void tuya_ble_connect_status_set(tuya_ble_connect_status_t status);
tuya_ble_connect_status_t tuya_ble_connect_status_get(void);
#if TUYA_BLE_LINK_LAYER_ENCRYPTION_SUPPORT_ENABLE
void tuya_ble_link_status_set(tuya_ble_link_status_t status);
tuya_ble_link_status_t tuya_ble_link_status_get(void);
#endif
void tuya_ble_event_init(void);
uint8_t tuya_ble_event_send(tuya_ble_evt_param_t *evt);
uint8_t tuya_ble_cb_event_send(tuya_ble_cb_evt_param_t *evt);
uint8_t tuya_ble_get_adv_connect_request_bit_status(void);
void tuya_ble_adv_change(void);
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN >= 3)
void tuya_ble_adv_change_with_connecting_request(void);
#endif
tuya_ble_status_t tuya_ble_inter_event_response(tuya_ble_cb_evt_param_t *param);
void tuya_ble_connect_monitor_timer_init(void);
void tuya_ble_connect_monitor_timer_start(void);
void tuya_ble_connect_monitor_timer_stop(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,54 +0,0 @@
/**
* \file tuya_ble_mem.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_MEM_H__
#define TUYA_BLE_MEM_H__
#include "tuya_ble_type.h"
#ifdef __cplusplus
extern "C" {
#endif
void *tuya_ble_malloc(uint16_t size);
tuya_ble_status_t tuya_ble_free(uint8_t *ptr);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,316 +0,0 @@
/**
* \file tuya_ble_mutli_tsf_protocol.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef _TUYA_BLE_MUTLI_TSF_PROTOCOL_H
#define _TUYA_BLE_MUTLI_TSF_PROTOCOL_H
#include "tuya_ble_stdlib.h"
#include "tuya_ble_config.h"
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __MUTLI_TSF_PROTOCOL_GLOBALS
#define __MUTLI_TSF_PROTOCOL_EXT
#else
#define __MUTLI_TSF_PROTOCOL_EXT extern
#endif
/***********************************************************
*************************micro define***********************
***********************************************************/
#define SNGL_PKG_TRSFR_LMT TUYA_BLE_DATA_MTU_MAX // single package transfer limit
//#define FRM_TYPE_OFFSET (0x0f << 4)
#define FRM_VERSION_OFFSET (0x0f << 4)
#define FRM_SEQ_OFFSET (0x0f << 0)
// frame total len
typedef uint32_t frame_total_t;
// frame subpackage num
typedef uint32_t frame_subpkg_num_t;
// frame sequence
typedef uint8_t frame_seq_t;
#define FRAME_SEQ_LMT 16
// frame subpackage len
typedef uint16_t frame_subpkg_len_t;
// frame package description
typedef uint8_t frm_pkg_desc_t;
#define FRM_PKG_INIT 0 // frame package init
#define FRM_PKG_FIRST 1 // frame package first
#define FRM_PKG_MIDDLE 2 // frame package middle
#define FRM_PKG_END 3 // frame package end
// mutil tsf ret code
typedef int32_t mtp_ret;
#define MTP_OK 0
#define MTP_INVALID_PARAM 1
#define MTP_COM_ERROR 2
#define MTP_TRSMITR_CONTINUE 3
#define MTP_TRSMITR_ERROR 4
#define MTP_MALLOC_ERR 5
// frame transmitter process
typedef struct {
frame_total_t total; //4 bytes, total length of data, not including header
uint8_t version; //1 byte, protocol major version number
frame_seq_t seq; //1 byte
frm_pkg_desc_t pkg_desc; //1 byte, Current packet frame type (init/first/middle/end)
frame_subpkg_num_t subpkg_num;//4 bytes, current sub-packet number
uint32_t pkg_trsmitr_cnt; // package process count ,Number of bytes sent
frame_subpkg_len_t subpkg_len;//1 byte, the data length in the current sub-packet
uint8_t subpkg[SNGL_PKG_TRSFR_LMT];
} frm_trsmitr_proc_s;
// dp type description,please refer to the relevant help documents of Tuya iot platform for the usage of various types of dp points.
typedef uint8_t dp_type;
#define DT_RAW 0
#define DT_BOOL 1
#define DT_VALUE 2
#define DT_INT DT_VALUE
#define DT_STRING 3
#define DT_ENUM 4
#define DT_BITMAP 5
#define DT_CHAR 7 //Not currently supported
#define DT_UCHAR 8 //Not currently supported
#define DT_SHORT 9 //Not currently supported
#define DT_USHORT 10 //Not currently supported
#define DT_LMT DT_USHORT
#define DT_VALUE_LEN 4 // int
#define DT_BOOL_LEN 1
#define DT_ENUM_LEN 1
#define DT_BITMAP_MAX 4 // 1/2/4
#define DT_STR_MAX 255
#define DT_RAW_MAX 255
#define DT_INT_LEN DT_VALUE_LEN
typedef struct s_klv_node {
struct s_klv_node *next;
uint8_t id;
dp_type type;
uint16_t len;
uint8_t *data;
} klv_node_s;
/***********************************************************
*************************variable define********************
***********************************************************/
/***********************************************************
*************************function define********************
***********************************************************/
/***********************************************************
* Function: make_klv_list
* description:
* Input:
* Output:
* Return:
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
klv_node_s *make_klv_list(klv_node_s *list, uint8_t id, dp_type type, \
void *data, uint16_t len);
/***********************************************************
* Function: free_klv_list
* description:
* Input: list
* Output:
* Return:
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
void free_klv_list(klv_node_s *list);
/***********************************************************
* Function: klvlist_2_data
* description:
* Input: list
* Output: data len
* Return:
* Note:data need free.
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
mtp_ret klvlist_2_data(klv_node_s *list, uint8_t **data, uint32_t *len, uint8_t type);
/***********************************************************
* Function: data_2_klvlist
* description:
* Input: data len
* Output: list
* Return:
* Note: list need to call free_klv_list to free.
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
mtp_ret data_2_klvlist(uint8_t *data, uint32_t len, klv_node_s **list, uint8_t type);
/***********************************************************
* Function: create_trsmitr_init
* description: create a transmitter and initialize
* Input: none
* Output:
* Return: transmitter handle
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
frm_trsmitr_proc_s *create_trsmitr_init(void);
/***********************************************************
* Function: trsmitr_init
* description: init a transmitter
* Input: transmitter handle
* Output:
* Return:
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
void trsmitr_init(frm_trsmitr_proc_s *frm_trsmitr);
/***********************************************************
* Function: delete_trsmitr
* description: delete transmitter
* Input: transmitter handle
* Output:
* Return:
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
void delete_trsmitr(frm_trsmitr_proc_s *frm_trsmitr);
/***********************************************************
* Function: get_trsmitr_frame_total_len
* description: get a transmitter total data len
* Input: transmitter handle
* Output:
* Return: frame_total_t
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
frame_total_t get_trsmitr_frame_total_len(frm_trsmitr_proc_s *frm_trsmitr);
/***********************************************************
* Function: get_trsmitr_frame_type
* description:
* Input: transmitter handle
* Output:
* Return: frame_type_t
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
uint8_t get_trsmitr_frame_version(frm_trsmitr_proc_s *frm_trsmitr);
/***********************************************************
* Function: get_trsmitr_frame_seq
* description:
* Input: transmitter handle
* Output:
* Return: frame_seq_t
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
frame_seq_t get_trsmitr_frame_seq(frm_trsmitr_proc_s *frm_trsmitr);
/***********************************************************
* Function: get_trsmitr_subpkg_len
* description:
* Input: transmitter handle
* Output:
* Return: frame_subpkg_len_t
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
frame_subpkg_len_t get_trsmitr_subpkg_len(frm_trsmitr_proc_s *frm_trsmitr);
/***********************************************************
* Function: get_trsmitr_subpkg
* description:
* Input: transmitter handle
* Output:
* Return: subpackage buf
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
uint8_t *get_trsmitr_subpkg(frm_trsmitr_proc_s *frm_trsmitr);
/***********************************************************
* Function: trsmitr_send_pkg_encode
* description: frm_trsmitr->transmitter handle
* type->frame type
* buf->data buf
* len->data len
* Input:
* Output:
* Return: MTP_OK->buf send up
* MTP_TRSMITR_CONTINUE->need call again to be continue
* other->error
* Note: could get from encode data len and encode data by calling method
get_trsmitr_subpkg_len() and get_trsmitr_subpkg()
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
mtp_ret trsmitr_send_pkg_encode(frm_trsmitr_proc_s *frm_trsmitr, uint8_t version, uint8_t *buf, uint32_t len);
/***********************************************************
* Function: trsmitr_send_pkg_encode_with_packet_length
* description: Encoding function for specifying sub-packet length
*
*
*
* Input:
* Output:
* Return: MTP_OK->buf send up
* MTP_TRSMITR_CONTINUE->need call again to be continue
* other->error
* Note: could get from encode data len and encode data by calling method
get_trsmitr_subpkg_len() and get_trsmitr_subpkg()
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
mtp_ret trsmitr_send_pkg_encode_with_packet_length(frm_trsmitr_proc_s *frm_trsmitr, uint32_t pkg_len_max, uint8_t version, uint8_t *buf, uint32_t len);
/***********************************************************
* Function: trsmitr_recv_pkg_decode
* description: frm_trsmitr->transmitter handle
* raw_data->raw encode data
* raw_data_len->raw encode data len
* Input:
* Output:
* Return: MTP_OK->buf receive up
* MTP_TRSMITR_CONTINUE->need call again to be continue
* other->error
* Note: could get from decode data len and decode data by calling method
get_trsmitr_subpkg_len() and get_trsmitr_subpkg()
***********************************************************/
__MUTLI_TSF_PROTOCOL_EXT \
mtp_ret trsmitr_recv_pkg_decode(frm_trsmitr_proc_s *frm_trsmitr, uint8_t *raw_data, uint16_t raw_data_len);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,56 +0,0 @@
/**
* \file tuya_ble_queue.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_QUEUE_H_
#define TUYA_BLE_QUEUE_H_
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#ifdef __cplusplus
extern "C" {
#endif
typedef struct {
void *buf;
volatile uint8_t size;
volatile uint8_t offset;
volatile uint8_t rd_ptr;
volatile uint8_t wr_ptr;
volatile uint8_t used;
} tuya_ble_queue_t;
tuya_ble_status_t tuya_ble_queue_init(tuya_ble_queue_t *q, void *buf, uint8_t size, uint8_t elem_size);
tuya_ble_status_t tuya_ble_enqueue(tuya_ble_queue_t *q, void *in);
tuya_ble_status_t tuya_ble_queue_get(tuya_ble_queue_t *q, void *out);
tuya_ble_status_t tuya_ble_dequeue(tuya_ble_queue_t *q, void *out);
void tuya_ble_queue_decrease(tuya_ble_queue_t *q);
void tuya_ble_queue_flush(tuya_ble_queue_t *q);
uint8_t tuya_ble_get_queue_used(tuya_ble_queue_t *q);
#ifdef __cplusplus
}
#endif
#endif //TUYA_BLE_QUEUE_H_

View File

@ -1,53 +0,0 @@
/**
* \file tuya_ble_storage.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_STORAGE_H_
#define TUYA_BLE_STORAGE_H_
#include "tuya_ble_type.h"
#include "tuya_ble_internal_config.h"
uint32_t tuya_ble_storage_save_sys_settings(void);
uint32_t tuya_ble_storage_save_auth_settings(void);
uint32_t tuya_ble_storage_init(void);
#if (TUYA_BLE_DEVICE_AUTH_DATA_STORE)
tuya_ble_status_t tuya_ble_storage_write_pid(tuya_ble_product_id_type_t pid_type, uint8_t pid_len, uint8_t *pid);
tuya_ble_status_t tuya_ble_storage_write_hid(uint8_t *hid, uint8_t len);
tuya_ble_status_t tuya_ble_storage_read_id_info(tuya_ble_factory_id_data_t *id);
tuya_ble_status_t tuya_ble_storage_write_auth_key_device_id_mac(uint8_t *auth_key, uint8_t auth_key_len, uint8_t *device_id, uint8_t device_id_len,
uint8_t *mac, uint8_t mac_len, uint8_t *mac_string, uint8_t mac_string_len, uint8_t *pid, uint8_t pid_len);
#endif
#endif

View File

@ -1,51 +0,0 @@
/**
* \file tuya_ble_unix_time.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_UNIX_TIME_H_
#define TUYA_BLE_UNIX_TIME_H_
#include "tuya_ble_stdlib.h"
/* time struct */
typedef struct {
uint16_t nYear;
uint8_t nMonth;
uint8_t nDay;
uint8_t nHour;
uint8_t nMin;
uint8_t nSec;
uint8_t DayIndex; /* 0 = Sunday */
} tuya_ble_time_struct_data_t;
void tuya_ble_utc_sec_2_mytime(uint32_t utc_sec, tuya_ble_time_struct_data_t *result, bool daylightSaving);
void tuya_ble_utc_sec_2_mytime_string(uint32_t utc_sec, bool daylightSaving, char *s);
uint32_t tuya_ble_mytime_2_utc_sec(tuya_ble_time_struct_data_t *currTime, bool daylightSaving);
#endif

View File

@ -1,123 +0,0 @@
/**
* \file tuya_ble_utils.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_UTILS_H_
#define TUYA_BLE_UTILS_H_
#include "tuya_ble_stdlib.h"
#define BSWAP_16(x) \
(uint16_t)((((uint16_t)(x) & 0x00ff) << 8) | \
(((uint16_t)(x) & 0xff00) >> 8) )
#define BSWAP_32(x) \
(uint32_t)((((uint32_t)(x) & 0xff000000) >> 24) | \
(((uint32_t)(x) & 0x00ff0000) >> 8) | \
(((uint32_t)(x) & 0x0000ff00) << 8) | \
(((uint32_t)(x) & 0x000000ff) << 24))
int32_t tuya_ble_rand_number(int32_t min, int32_t max);
int32_t tuya_ble_count_bits(uint32_t data);
void tuya_ble_inverted_array(uint8_t *array, uint16_t length);
bool tuya_ble_buffer_value_is_all_x(uint8_t *buffer, uint16_t len, uint8_t value);
uint8_t tuya_ble_check_sum(uint8_t *pbuf, uint16_t len);
uint8_t tuya_ble_check_num(uint8_t *buf, uint8_t num);
void tuya_ble_hextoascii(uint8_t *hexbuf, uint8_t len, uint8_t *ascbuf);
void tuya_ble_hextostr(uint8_t *hexbuf, uint8_t len, uint8_t *strbuf);
void tuya_ble_asciitohex(uint8_t *ascbuf, uint8_t *hexbuf);
uint8_t tuya_ble_char_2_ascii(uint8_t data);
void tuya_ble_str_to_hex(uint8_t *str_buf, uint8_t str_len, uint8_t *hex_buf);
bool tuya_ble_is_word_aligned_tuya(void const *p);
uint16_t tuya_ble_crc16_compute(uint8_t *p_data, uint16_t size, uint16_t *p_crc);
uint32_t tuya_ble_crc32_compute(uint8_t const *p_data, uint32_t size, uint32_t const *p_crc);
void tuya_ble_device_id_20_to_16(uint8_t *in, uint8_t *out);
void tuya_ble_device_id_16_to_20(uint8_t *in, uint8_t *out);
char tuya_ble_hexstr2hex(uint8_t *hexstr, int32_t len, uint8_t *hex);
/**
* @brief Function for search character/symbol index from input string
*
* @param
* [in]data : pointer to input data
* [in]data : Number of bytes of data
* [in]symbol : Search symbol or character, Such as ':' or ','
* [out]index[] : Array of indexs
*
* @return The number of matched character/symbol
*
* @note
*
* */
int32_t tuya_ble_search_symbol_index(char *data, uint16_t len, char symbol, uint8_t index[]);
int32_t tuya_ble_ascii_to_int(char *ascii, uint16_t len);
/**
* @brief Function for pem format ecc key to hex foramt
*
* @param
* [in]pem : pointer to pem data
* [out]key : pointer to output data, hex format ecc key
* [out]key_len: Number of bytes of key.
*
* @return 0 - failed, 1 - success
*
* @note developer could use tuya_ble_ecc_key_pem2hex_example() function to test
*
* */
int32_t tuya_ble_ecc_key_pem2hex(const char *pem, uint8_t *key, uint16_t *key_len);
/**
* @brief Function for extract r+s from der from ecdsa sign
*
* @param
* [in]der : pointer to der data
* [out]raw_rs : pointer to output data, the raw data[r+s] of der
*
* @return 0 - failed, 1 - success
*
* @note
*
* */
int32_t tuya_ble_ecc_sign_secp256r1_extract_raw_from_der(const char *der, uint8_t *raw_rs);
#endif /* TUYA_UTILS_H_ */

View File

@ -1,99 +0,0 @@
/**
* \file tuya_ble_event_handler.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_EVENT_HANDLER_H__
#define TUYA_BLE_EVENT_HANDLER_H__
#include "tuya_ble_type.h"
#ifdef __cplusplus
extern "C" {
#endif
void tuya_ble_handle_device_info_update_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_reported_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_with_time_reported_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_with_time_string_reported_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_with_flag_reported_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_with_flag_and_time_reported_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_with_flag_and_time_string_reported_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_send_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_dp_data_with_time_send_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_device_unbind_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_factory_reset_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_ota_response_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_bulk_data_evt(tuya_ble_evt_param_t *p_evt);
void tuya_ble_handle_data_passthrough_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_data_prod_test_response_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_uart_cmd_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_ble_cmd_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_net_config_response_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_time_request_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_extend_time_request_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_unbound_response_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_anomaly_unbound_response_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_device_reset_response_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_connect_change_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_ble_data_evt(uint8_t *buf, uint16_t len);
void tuya_ble_handle_connecting_request_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_link_update_evt(tuya_ble_evt_param_t *evt);
void tuya_ble_handle_weather_data_request_evt(tuya_ble_evt_param_t *evt);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -1,74 +0,0 @@
/**
* \file tuya_ble_secure.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_SECURE_H_
#define TUYA_BLE_SECURE_H_
#include "tuya_ble_type.h"
#ifdef __cplusplus
extern "C" {
#endif
enum {
ENCRYPTION_MODE_NONE,
ENCRYPTION_MODE_KEY_1,
ENCRYPTION_MODE_KEY_2,
ENCRYPTION_MODE_KEY_3,
ENCRYPTION_MODE_KEY_4,
ENCRYPTION_MODE_SESSION_KEY,
ENCRYPTION_MODE_ECDH_KEY,
ENCRYPTION_MODE_FTM_KEY,
ENCRYPTION_MODE_MAX,
};
bool tuya_ble_register_key_generate(uint8_t *output, tuya_ble_parameters_settings_t *current_para);
uint8_t tuya_ble_encryption(uint16_t protocol_version, uint8_t encryption_mode, uint8_t *iv, uint8_t *in_buf, uint32_t in_len, uint32_t *out_len, uint8_t *out_buf, tuya_ble_parameters_settings_t *current_para_data, uint8_t *dev_rand);
uint8_t tuya_ble_encrypt_old_with_key(uint8_t *key, uint8_t *in_buf, uint8_t in_len, uint8_t *out_buf);
bool tuya_ble_device_id_encrypt(uint8_t *key_in, uint16_t key_len, uint8_t *input, uint16_t input_len, uint8_t *output);
bool tuya_ble_device_id_decrypt(uint8_t *key_in, uint16_t key_len, uint8_t *input, uint16_t input_len, uint8_t *output);
bool tuya_ble_device_id_encrypt_v4(uint8_t *key_in, uint16_t key_len, uint8_t *input, uint16_t input_len, uint8_t *output);
uint8_t tuya_ble_decryption(uint16_t protocol_version, uint8_t const *in_buf, uint32_t in_len, uint32_t *out_len, uint8_t *out_buf, tuya_ble_parameters_settings_t *current_para_data, uint8_t *dev_rand);
bool tuya_ble_server_cert_data_verify(const uint8_t *p_data, uint16_t data_len, const uint8_t *p_sig);
bool tuya_ble_sig_data_verify(const uint8_t *p_pk, const uint8_t *p_data, uint16_t data_len, const uint8_t *p_sig);
void tuya_ble_event_process(tuya_ble_evt_param_t *tuya_ble_evt);
#ifdef __cplusplus
}
#endif
#endif // TUYA_BLE_SECURE_H_

View File

@ -1,278 +0,0 @@
/**
* \file tuya_ble_bulkdata.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_bulk_data.h"
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_main.h"
#include "tuya_ble_internal_config.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_mutli_tsf_protocol.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_secure.h"
#include "tuya_ble_main.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_unix_time.h"
#include "tuya_ble_log.h"
#include "tuya_ble_gatt_send_queue.h"
uint32_t tuya_ble_bulk_data_read_block_size_get(void)
{
uint32_t mtu_length = 0;
uint32_t read_block_size = 0;
if (tuya_ble_connect_status_get() != BONDING_CONN) {
read_block_size = 0;
} else {
mtu_length = tuya_ble_send_packet_data_length_get();
if (mtu_length < 100) {
read_block_size = 256;
} else if ((mtu_length >= 100) && (mtu_length < 150)) {
read_block_size = 512;
} else {
read_block_size = TUYA_BLE_BULK_DATA_MAX_READ_BLOCK_SIZE;
}
}
return read_block_size;
}
void tuya_ble_handle_bulk_data_req(uint16_t cmd, uint8_t *p_recv_data, uint32_t recv_data_len)
{
uint16_t data_len;
tuya_ble_cb_evt_param_t event;
uint8_t err_code = 0;
data_len = (p_recv_data[11] << 8) + p_recv_data[12];
if (data_len == 0) {
return;
} else if (p_recv_data[13] != 0) { /*Currently only supports version 0*/
return;
} else {
}
event.evt = TUYA_BLE_CB_EVT_BULK_DATA;
switch (cmd) {
case FRM_BULK_DATA_READ_INFO_REQ:
event.bulk_req_data.evt = TUYA_BLE_BULK_DATA_EVT_READ_INFO;
event.bulk_req_data.bulk_type = p_recv_data[14];
break;
case FRM_BULK_DATA_READ_DATA_REQ:
event.bulk_req_data.evt = TUYA_BLE_BULK_DATA_EVT_READ_BLOCK;
event.bulk_req_data.bulk_type = p_recv_data[14];
event.bulk_req_data.params.block_data_req_data.block_number = (p_recv_data[15] << 8) + p_recv_data[16];
break;
case FRM_BULK_DATA_ERASE_DATA_REQ:
event.bulk_req_data.evt = TUYA_BLE_BULK_DATA_EVT_ERASE;
event.bulk_req_data.bulk_type = p_recv_data[14];
break;
default:
err_code = 1;
break;
}
if (err_code == 0) {
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_bulk_data_req-tuya ble send cb event failed.");
}
}
}
tuya_ble_status_t tuya_ble_bulk_data_response(tuya_ble_bulk_data_response_t *p_data)
{
tuya_ble_evt_param_t evt;
if (tuya_ble_connect_status_get() != BONDING_CONN) {
return TUYA_BLE_ERR_INVALID_STATE;
}
if ((p_data->evt == TUYA_BLE_BULK_DATA_EVT_SEND_DATA) && (p_data->params.send_res_data.current_block_length > (TUYA_BLE_SEND_MAX_DATA_LEN - 8))) {
return TUYA_BLE_ERR_INVALID_LENGTH;
}
evt.hdr.event = TUYA_BLE_EVT_BULK_DATA_RESPONSE;
memcpy(&evt.bulk_res_data, p_data, sizeof(tuya_ble_bulk_data_response_t));
if (p_data->evt == TUYA_BLE_BULK_DATA_EVT_SEND_DATA) {
evt.bulk_res_data.params.send_res_data.p_current_block_data = NULL;
evt.bulk_res_data.params.send_res_data.p_current_block_data = (uint8_t *)tuya_ble_malloc(p_data->params.send_res_data.current_block_length);
if (evt.bulk_res_data.params.send_res_data.p_current_block_data == NULL) {
return TUYA_BLE_ERR_NO_MEM;
}
memcpy(evt.bulk_res_data.params.send_res_data.p_current_block_data, p_data->params.send_res_data.p_current_block_data, p_data->params.send_res_data.current_block_length);
}
if (tuya_ble_event_send(&evt) != 0) {
if (p_data->evt == TUYA_BLE_BULK_DATA_EVT_SEND_DATA) {
tuya_ble_free(evt.bulk_res_data.params.send_res_data.p_current_block_data);
}
return TUYA_BLE_ERR_NO_EVENT;
}
return TUYA_BLE_SUCCESS;
}
void tuya_ble_handle_bulk_data_evt(tuya_ble_evt_param_t *evt)
{
uint16_t bulk_data_cmd = 0;
uint8_t buffer[14];
uint8_t *p_buf = NULL;
uint16_t data_length = 0;
uint8_t encry_mode = 0;
tuya_ble_cb_evt_param_t event;
uint8_t err_code = 0;
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
buffer[0] = 0;
buffer[1] = evt->bulk_res_data.bulk_type;
switch (evt->bulk_res_data.evt) {
case TUYA_BLE_BULK_DATA_EVT_READ_INFO:
bulk_data_cmd = FRM_BULK_DATA_READ_INFO_RESP;
buffer[2] = evt->bulk_res_data.params.bulk_info_res_data.status;
buffer[3] = evt->bulk_res_data.params.bulk_info_res_data.flag;
buffer[4] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_length >> 24;
buffer[5] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_length >> 16;
buffer[6] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_length >> 8;
buffer[7] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_length;
buffer[8] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_crc >> 24;
buffer[9] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_crc >> 16;
buffer[10] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_crc >> 8;
buffer[11] = evt->bulk_res_data.params.bulk_info_res_data.bulk_data_crc;
buffer[12] = evt->bulk_res_data.params.bulk_info_res_data.block_data_length >> 8;
buffer[13] = evt->bulk_res_data.params.bulk_info_res_data.block_data_length;
data_length = 14;
break;
case TUYA_BLE_BULK_DATA_EVT_READ_BLOCK:
bulk_data_cmd = FRM_BULK_DATA_READ_DATA_RESP;
buffer[2] = evt->bulk_res_data.params.block_res_data.status;
buffer[3] = evt->bulk_res_data.params.block_res_data.block_number >> 8;
buffer[4] = evt->bulk_res_data.params.block_res_data.block_number;
buffer[5] = evt->bulk_res_data.params.block_res_data.block_data_length >> 8;
buffer[6] = evt->bulk_res_data.params.block_res_data.block_data_length;
buffer[7] = evt->bulk_res_data.params.block_res_data.max_packet_data_length >> 8;
buffer[8] = evt->bulk_res_data.params.block_res_data.max_packet_data_length;
buffer[9] = evt->bulk_res_data.params.block_res_data.block_data_crc16 >> 8;
buffer[10] = evt->bulk_res_data.params.block_res_data.block_data_crc16;
data_length = 11;
break;
case TUYA_BLE_BULK_DATA_EVT_SEND_DATA :
bulk_data_cmd = FRM_BULK_DATA_SEND_DATA;
p_buf = (uint8_t *)tuya_ble_malloc(evt->bulk_res_data.params.send_res_data.current_block_length + 8);
if (p_buf) {
p_buf[0] = 0;
p_buf[1] = evt->bulk_res_data.bulk_type;
p_buf[2] = evt->bulk_res_data.params.send_res_data.current_block_number >> 8;
p_buf[3] = evt->bulk_res_data.params.send_res_data.current_block_number;
p_buf[4] = 0;
p_buf[5] = 0;
p_buf[6] = evt->bulk_res_data.params.send_res_data.current_block_length >> 8;
p_buf[7] = evt->bulk_res_data.params.send_res_data.current_block_length;
memcpy(&p_buf[8], evt->bulk_res_data.params.send_res_data.p_current_block_data, evt->bulk_res_data.params.send_res_data.current_block_length);
data_length = evt->bulk_res_data.params.send_res_data.current_block_length + 8;
}
tuya_ble_free(evt->bulk_res_data.params.send_res_data.p_current_block_data);
break;
case TUYA_BLE_BULK_DATA_EVT_ERASE :
bulk_data_cmd = FRM_BULK_DATA_ERASE_DATA_RESP;
buffer[2] = evt->bulk_res_data.params.erase_res_data.status;
data_length = 3;
break;
default:
break;
}
if (data_length > 0) {
if (evt->bulk_res_data.evt == TUYA_BLE_BULK_DATA_EVT_READ_BLOCK) {
err_code = tuya_ble_commData_send(bulk_data_cmd, 0, buffer, data_length, encry_mode);
if (evt->bulk_res_data.params.block_res_data.status == 0) {
event.evt = TUYA_BLE_CB_EVT_BULK_DATA;
event.bulk_req_data.evt = TUYA_BLE_BULK_DATA_EVT_SEND_DATA;
event.bulk_req_data.bulk_type = evt->bulk_res_data.bulk_type;
event.bulk_req_data.params.send_data_req_data.block_number = evt->bulk_res_data.params.block_res_data.block_number;
if (!err_code) {
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_bulk_data_evt-tuya ble send cb event failed.");
}
} else {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_bulk_data_evt-response read bulk data error.");
}
}
} else if (evt->bulk_res_data.evt == TUYA_BLE_BULK_DATA_EVT_SEND_DATA) {
err_code = tuya_ble_commData_send(bulk_data_cmd, 0, p_buf, data_length, encry_mode);
tuya_ble_free(p_buf);
} else {
tuya_ble_commData_send(bulk_data_cmd, 0, buffer, data_length, encry_mode);
}
}
}

View File

@ -1,225 +0,0 @@
/**
* \file tuya_ble_event.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_main.h"
#include "tuya_ble_secure.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_sdk_version.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_event.h"
#include "tuya_ble_log.h"
#if (!TUYA_BLE_USE_OS)
static uint8_t *m_queue_event_data; /**< Array for holding the queue event data. */
static volatile uint8_t m_queue_start_index; /**< Index of queue entry at the start of the queue. */
static volatile uint8_t m_queue_end_index; /**< Index of queue entry at the end of the queue. */
static uint16_t m_queue_event_size; /**< Maximum event size in queue. */
static uint16_t m_queue_size; /**< Number of queue entries. */
/**@brief Function for incrementing a queue index, and handle wrap-around.
*
* @param[in] index Old index.
*
* @return New (incremented) index.
*/
static __TUYA_BLE_INLINE uint8_t next_index(uint8_t index)
{
return (index < m_queue_size) ? (index + 1) : 0;
}
static __TUYA_BLE_INLINE uint8_t tuya_sched_queue_full(void)
{
uint8_t tmp = m_queue_start_index;
return next_index(m_queue_end_index) == tmp;
}
/**@brief Macro for checking if a queue is full. */
#define TUYA_BLE_SCHED_QUEUE_FULL() tuya_sched_queue_full()
static __TUYA_BLE_INLINE uint8_t tuya_sched_queue_empty(void)
{
uint8_t tmp = m_queue_start_index;
return m_queue_end_index == tmp;
}
/**@brief Macro for checking if a queue is empty. */
#define TUYA_BLE_SCHED_QUEUE_EMPTY() tuya_sched_queue_empty()
uint32_t tuya_ble_sched_init(uint16_t event_size, uint16_t queue_size, void *p_event_buffer)
{
// Check that buffer is correctly aligned
if (!tuya_ble_is_word_aligned_tuya(p_event_buffer)) {
TUYA_BLE_LOG_ERROR("tuya_ble_sched_init error");
return 1;
}
// Initialize event scheduler
m_queue_event_data = &((uint8_t *)p_event_buffer)[0];
m_queue_end_index = 0;
m_queue_start_index = 0;
m_queue_event_size = event_size;
m_queue_size = queue_size;
return 0;
}
uint16_t tuya_ble_sched_queue_size_get(void)
{
return m_queue_size;
}
uint16_t tuya_ble_sched_queue_space_get(void)
{
uint16_t start = m_queue_start_index;
uint16_t end = m_queue_end_index;
uint16_t free_space = m_queue_size - ((end >= start) ?
(end - start) : (m_queue_size + 1 - start + end));
return free_space;
}
uint16_t tuya_ble_sched_queue_events_get(void)
{
uint16_t start = m_queue_start_index;
uint16_t end = m_queue_end_index;
uint16_t number_of_events;
if (m_queue_size == 0) {
number_of_events = 0;
} else {
number_of_events = ((end >= start) ? (end - start) : (m_queue_size + 1 - start + end));
}
return number_of_events;
}
static tuya_ble_status_t tuya_ble_sched_event_put(void const *p_event_data, uint16_t event_data_size)
{
tuya_ble_status_t err_code;
if (event_data_size <= m_queue_event_size) {
uint16_t event_index = 0xFFFF;
tuya_ble_device_enter_critical();
if (!TUYA_BLE_SCHED_QUEUE_FULL()) {
event_index = m_queue_end_index;
m_queue_end_index = next_index(m_queue_end_index);
}
tuya_ble_device_exit_critical();
if (event_index != 0xFFFF) {
// NOTE: This can be done outside the critical region since the event consumer will
// always be called from the main loop, and will thus never interrupt this code.
if ((p_event_data != NULL) && (event_data_size > 0)) {
memcpy(&m_queue_event_data[event_index * m_queue_event_size],
p_event_data,
event_data_size);
} else {
}
err_code = TUYA_BLE_SUCCESS;
} else {
err_code = TUYA_BLE_ERR_NO_MEM;
}
} else {
err_code = TUYA_BLE_ERR_INVALID_LENGTH;
}
return err_code;
}
void tuya_sched_execute(void)
{
static tuya_ble_evt_param_t tuya_ble_evt;
tuya_ble_evt_param_t *evt;
evt = &tuya_ble_evt;
uint8_t end_ix = m_queue_end_index;
while (m_queue_start_index != end_ix) { //(!TUYA_BLE_SCHED_QUEUE_EMPTY())
// Since this function is only called from the main loop, there is no
// need for a critical region here, however a special care must be taken
// regarding update of the queue start index (see the end of the loop).
uint16_t event_index = m_queue_start_index;
void *p_event_data;
p_event_data = &(m_queue_event_data[event_index * m_queue_event_size]);
memcpy(evt, p_event_data, sizeof(tuya_ble_evt_param_t));
//TUYA_BLE_LOG_DEBUG("TUYA_RECEIVE_EVT-0x%04x,start index-0x%04x,end index-0x%04x\n",evt->hdr.event,m_queue_start_index,m_queue_end_index);
tuya_ble_event_process(evt);
// Event processed, now it is safe to move the queue start index,
// so the queue entry occupied by this event can be used to store
// a next one.
m_queue_start_index = next_index(m_queue_start_index);
}
}
void tuya_ble_event_queue_init(void)
{
if ((sizeof(tuya_ble_evt_param_t)) > TUYA_BLE_EVT_SIZE) {
TUYA_BLE_LOG_ERROR("ERROR!!TUYA_BLE_EVT_SIZE is not enough!");
return;
}
TUYA_BLE_SCHED_INIT(TUYA_BLE_EVT_SIZE, TUYA_BLE_EVT_MAX_NUM);
}
tuya_ble_status_t tuya_ble_message_send(tuya_ble_evt_param_t *evt)
{
return tuya_ble_sched_event_put(evt, m_queue_event_size);
}
#endif

View File

@ -1,779 +0,0 @@
/**
* \file tuya_ble_event_handler.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_main.h"
#include "tuya_ble_secure.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_sdk_version.h"
#include "tuya_ble_event.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_app_uart_common_handler.h"
#include "tuya_ble_app_production_test.h"
#include "tuya_ble_log.h"
#include "tuya_ble_event_handler.h"
void tuya_ble_handle_device_info_update_evt(tuya_ble_evt_param_t *evt)
{
#if (!TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
tuya_ble_cb_evt_param_t event;
tuya_ble_connect_status_t current_connect_status;
#endif
switch (evt->device_info_data.type) {
case DEVICE_INFO_TYPE_PID:
tuya_ble_current_para.pid_type = TUYA_BLE_PRODUCT_ID_TYPE_PID;
tuya_ble_current_para.pid_len = evt->device_info_data.len;
memcpy(tuya_ble_current_para.pid, evt->device_info_data.data, tuya_ble_current_para.pid_len);
tuya_ble_adv_change();
break;
case DEVICE_INFO_TYPE_PRODUCT_KEY:
tuya_ble_current_para.pid_type = TUYA_BLE_PRODUCT_ID_TYPE_PRODUCT_KEY;
tuya_ble_current_para.pid_len = evt->device_info_data.len;
memcpy(tuya_ble_current_para.pid, evt->device_info_data.data, tuya_ble_current_para.pid_len);
tuya_ble_adv_change();
break;
case DEVICE_INFO_TYPE_LOGIN_KEY:
#if (!TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
if (memcmp(tuya_ble_current_para.sys_settings.login_key, evt->device_info_data.data, LOGIN_KEY_LEN)) {
memcpy(tuya_ble_current_para.sys_settings.login_key, evt->device_info_data.data, LOGIN_KEY_LEN);
}
#endif
break;
case DEVICE_INFO_TYPE_BOUND:
#if (!TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
if (tuya_ble_current_para.sys_settings.bound_flag != evt->device_info_data.data[0]) {
tuya_ble_current_para.sys_settings.bound_flag = evt->device_info_data.data[0];
tuya_ble_adv_change();
current_connect_status = tuya_ble_connect_status_get();
if (tuya_ble_current_para.sys_settings.bound_flag == 1) { //0->1
if (current_connect_status == UNBONDING_CONN) {
tuya_ble_connect_status_set(BONDING_CONN);
} else if (current_connect_status == UNBONDING_UNAUTH_CONN) {
tuya_ble_connect_status_set(BONDING_UNAUTH_CONN);
} else if (current_connect_status == UNBONDING_UNCONN) {
tuya_ble_connect_status_set(BONDING_UNCONN);
} else {
}
} else { //1->0
if (current_connect_status == BONDING_CONN) {
tuya_ble_connect_status_set(UNBONDING_CONN);
} else if (current_connect_status == BONDING_UNAUTH_CONN) {
tuya_ble_connect_status_set(UNBONDING_UNAUTH_CONN);
} else if (current_connect_status == BONDING_UNCONN) {
tuya_ble_connect_status_set(UNBONDING_UNCONN);
} else {
}
}
event.evt = TUYA_BLE_CB_EVT_CONNECTE_STATUS;
event.connect_status = tuya_ble_connect_status_get();
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya ble send cb event failed.");
} else {
TUYA_BLE_LOG_ERROR("tuya ble send cb event succeed.");
}
}
#endif
break;
default:
break;
}
}
void tuya_ble_handle_dp_data_reported_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
tuya_ble_commData_send(FRM_STAT_REPORT, 0, evt->reported_data.p_data, evt->reported_data.data_len, encry_mode);
if (evt->reported_data.p_data) {
tuya_ble_free(evt->reported_data.p_data);
}
}
void tuya_ble_handle_dp_data_with_flag_reported_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
tuya_ble_commData_send(FRM_DATA_WITH_FLAG_REPORT, 0, evt->flag_reported_data.p_data, evt->flag_reported_data.data_len, encry_mode);
if (evt->flag_reported_data.p_data) {
tuya_ble_free(evt->flag_reported_data.p_data);
}
}
void tuya_ble_handle_dp_data_with_time_reported_evt(tuya_ble_evt_param_t *evt)
{
uint8_t *data_buffer = NULL;
uint16_t data_len;
uint8_t encry_mode = 0;
data_len = 5 + evt->reported_with_time_data.data_len;
data_buffer = (uint8_t *)tuya_ble_malloc(data_len);
if (data_buffer == NULL) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_dp_data_with_time_reported_evt malloc failed.");
if (evt->reported_with_time_data.p_data) {
tuya_ble_free(evt->reported_with_time_data.p_data);
}
return;
} else {
memset(data_buffer, 0, data_len);
}
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
data_buffer[0] = 1;
data_buffer[1] = evt->reported_with_time_data.timestamp >> 24;
data_buffer[2] = evt->reported_with_time_data.timestamp >> 16;
data_buffer[3] = evt->reported_with_time_data.timestamp >> 8;
data_buffer[4] = evt->reported_with_time_data.timestamp;
memcpy(&data_buffer[5], evt->reported_with_time_data.p_data, evt->reported_with_time_data.data_len);
tuya_ble_commData_send(FRM_STAT_WITH_TIME_REPORT, 0, data_buffer, data_len, encry_mode);
tuya_ble_free(data_buffer);
if (evt->reported_with_time_data.p_data) {
tuya_ble_free(evt->reported_with_time_data.p_data);
}
}
void tuya_ble_handle_dp_data_with_flag_and_time_reported_evt(tuya_ble_evt_param_t *evt)
{
uint8_t *data_buffer = NULL;
uint16_t data_len;
uint8_t encry_mode = 0;
data_len = 8 + evt->flag_reported_with_time_data.data_len;
data_buffer = (uint8_t *)tuya_ble_malloc(data_len);
if (data_buffer == NULL) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_dp_data_with_flag_and_time_reported_evt malloc failed.");
if (evt->flag_reported_with_time_data.p_data) {
tuya_ble_free(evt->flag_reported_with_time_data.p_data);
}
return;
} else {
memset(data_buffer, 0, data_len);
}
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
data_buffer[0] = evt->flag_reported_with_time_data.sn >> 8;
data_buffer[1] = evt->flag_reported_with_time_data.sn;
data_buffer[2] = evt->flag_reported_with_time_data.mode;
data_buffer[3] = 1;
data_buffer[4] = evt->flag_reported_with_time_data.timestamp >> 24;
data_buffer[5] = evt->flag_reported_with_time_data.timestamp >> 16;
data_buffer[6] = evt->flag_reported_with_time_data.timestamp >> 8;
data_buffer[7] = evt->flag_reported_with_time_data.timestamp;
memcpy(&data_buffer[8], evt->flag_reported_with_time_data.p_data, evt->flag_reported_with_time_data.data_len);
tuya_ble_commData_send(FRM_DATA_WITH_FLAG_AND_TIME_REPORT, 0, data_buffer, data_len, encry_mode);
tuya_ble_free(data_buffer);
if (evt->flag_reported_with_time_data.p_data) {
tuya_ble_free(evt->flag_reported_with_time_data.p_data);
}
}
void tuya_ble_handle_dp_data_with_time_string_reported_evt(tuya_ble_evt_param_t *evt)
{
uint8_t *data_buffer = NULL;
uint16_t data_len;
uint8_t encry_mode = 0;
data_len = 14 + evt->reported_with_time_string_data.data_len;
data_buffer = (uint8_t *)tuya_ble_malloc(data_len);
if (data_buffer == NULL) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_dp_data_with_time_string_reported_evt malloc failed.");
if (evt->reported_with_time_string_data.p_data) {
tuya_ble_free(evt->reported_with_time_string_data.p_data);
}
return;
} else {
memset(data_buffer, 0, data_len);
}
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
data_buffer[0] = 0;
memcpy(&data_buffer[1], evt->reported_with_time_string_data.time_string, 13);
memcpy(&data_buffer[14], evt->reported_with_time_string_data.p_data, evt->reported_with_time_string_data.data_len);
tuya_ble_commData_send(FRM_STAT_WITH_TIME_REPORT, 0, data_buffer, data_len, encry_mode);
tuya_ble_free(data_buffer);
if (evt->reported_with_time_string_data.p_data) {
tuya_ble_free(evt->reported_with_time_string_data.p_data);
}
}
void tuya_ble_handle_dp_data_with_flag_and_time_string_reported_evt(tuya_ble_evt_param_t *evt)
{
uint8_t *data_buffer = NULL;
uint16_t data_len;
uint8_t encry_mode = 0;
data_len = 17 + evt->flag_reported_with_time_string_data.data_len;
data_buffer = (uint8_t *)tuya_ble_malloc(data_len);
if (data_buffer == NULL) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_dp_data_with_flag_and_time_string_reported_evt malloc failed.");
if (evt->flag_reported_with_time_string_data.p_data) {
tuya_ble_free(evt->flag_reported_with_time_string_data.p_data);
}
return;
} else {
memset(data_buffer, 0, data_len);
}
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
data_buffer[0] = evt->flag_reported_with_time_string_data.sn >> 8;
data_buffer[1] = evt->flag_reported_with_time_string_data.sn;
data_buffer[2] = evt->flag_reported_with_time_string_data.mode;
data_buffer[3] = 0;
memcpy(&data_buffer[4], evt->flag_reported_with_time_string_data.time_string, 13);
memcpy(&data_buffer[17], evt->flag_reported_with_time_string_data.p_data, evt->flag_reported_with_time_string_data.data_len);
tuya_ble_commData_send(FRM_DATA_WITH_FLAG_AND_TIME_REPORT, 0, data_buffer, data_len, encry_mode);
tuya_ble_free(data_buffer);
if (evt->flag_reported_with_time_string_data.p_data) {
tuya_ble_free(evt->flag_reported_with_time_string_data.p_data);
}
}
void tuya_ble_handle_dp_data_send_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
tuya_ble_commData_send(FRM_DP_DATA_SEND_REQ, 0, evt->dp_send_data.p_data, evt->dp_send_data.data_len, encry_mode);
if (evt->dp_send_data.p_data) {
tuya_ble_free(evt->dp_send_data.p_data);
}
}
void tuya_ble_handle_dp_data_with_time_send_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
tuya_ble_commData_send(FRM_DP_DATA_WITH_TIME_SEND_REQ, 0, evt->dp_with_time_send_data.p_data, evt->dp_with_time_send_data.data_len, encry_mode);
if (evt->dp_with_time_send_data.p_data) {
tuya_ble_free(evt->dp_with_time_send_data.p_data);
}
}
void tuya_ble_handle_device_unbind_evt(tuya_ble_evt_param_t *evt)
{
tuya_ble_cb_evt_param_t event;
tuya_ble_device_unbond();
event.evt = TUYA_BLE_CB_EVT_CONNECTE_STATUS;
event.connect_status = tuya_ble_connect_status_get();
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_factory_reset_evt-tuya ble send cb event (connect status update) failed.");
} else {
}
event.evt = TUYA_BLE_CB_EVT_UNBIND_RESET_RESPONSE;
event.reset_response_data.type = RESET_TYPE_UNBIND;
event.reset_response_data.status = 0;
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_device_unbind_evt-tuya ble send cb event (TUYA_BLE_CB_EVT_UNBIND_RESET_RESPONSE) failed.");
} else {
}
}
void tuya_ble_handle_factory_reset_evt(tuya_ble_evt_param_t *evt)
{
tuya_ble_cb_evt_param_t event;
memset(tuya_ble_current_para.sys_settings.device_virtual_id, 0, DEVICE_VIRTUAL_ID_LEN);
tuya_ble_device_unbond();
event.evt = TUYA_BLE_CB_EVT_CONNECTE_STATUS;
event.connect_status = tuya_ble_connect_status_get();
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_factory_reset_evt-tuya ble send cb event (connect status update) failed.");
} else {
}
event.evt = TUYA_BLE_CB_EVT_UNBIND_RESET_RESPONSE;
event.reset_response_data.type = RESET_TYPE_FACTORY_RESET;
event.reset_response_data.status = 0;
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_factory_reset_evt-tuya ble send cb event (TUYA_BLE_CB_EVT_UNBIND_RESET_RESPONSE) failed.");
} else {
}
}
void tuya_ble_handle_ota_response_evt(tuya_ble_evt_param_t *evt)
{
uint16_t ota_cmd_type = 0;
uint8_t encry_mode = 0;
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
switch (evt->ota_response_data.type) {
case TUYA_BLE_OTA_REQ:
ota_cmd_type = FRM_OTA_START_REQ;
break;
case TUYA_BLE_OTA_FILE_INFO:
ota_cmd_type = FRM_OTA_FILE_INFOR_REQ;
break;
case TUYA_BLE_OTA_FILE_OFFSET_REQ :
ota_cmd_type = FRM_OTA_FILE_OFFSET_REQ;
break;
case TUYA_BLE_OTA_DATA :
ota_cmd_type = FRM_OTA_DATA_REQ;
break;
case TUYA_BLE_OTA_END :
ota_cmd_type = FRM_OTA_END_REQ;
break;
default:
break;
}
if (ota_cmd_type != 0) {
tuya_ble_commData_send(ota_cmd_type, 0, evt->ota_response_data.p_data, evt->ota_response_data.data_len, encry_mode);
}
if (evt->ota_response_data.p_data) {
tuya_ble_free(evt->ota_response_data.p_data);
}
}
void tuya_ble_handle_data_passthrough_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
if (tuya_ble_current_para.sys_settings.bound_flag) {
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
} else {
encry_mode = ENCRYPTION_MODE_KEY_2;
}
tuya_ble_commData_send(FRM_DATA_PASSTHROUGH_REQ, 0, evt->passthrough_data.p_data, evt->passthrough_data.data_len, encry_mode);
if (evt->passthrough_data.p_data) {
tuya_ble_free(evt->passthrough_data.p_data);
}
}
void tuya_ble_handle_data_prod_test_response_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
tuya_ble_connect_status_t connect_status;
if (evt->prod_test_res_data.channel == 0) {
tuya_ble_common_uart_send_data(evt->prod_test_res_data.p_data, evt->prod_test_res_data.data_len);
} else if (evt->prod_test_res_data.channel == 1) {
connect_status = tuya_ble_connect_status_get();
if (connect_status == BONDING_CONN) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
#if (TUYA_BLE_PROD_TEST_SUPPORT_ENCRYPTION != 0)
encry_mode = ENCRYPTION_MODE_FTM_KEY;
#else
encry_mode = ENCRYPTION_MODE_NONE;
#endif
}
tuya_ble_commData_send(FRM_FACTORY_TEST_RESP, 0, evt->prod_test_res_data.p_data, evt->prod_test_res_data.data_len, encry_mode);
}
if (evt->prod_test_res_data.p_data) {
tuya_ble_free(evt->prod_test_res_data.p_data);
}
}
void tuya_ble_handle_uart_cmd_evt(tuya_ble_evt_param_t *evt)
{
uint8_t sum;
uint8_t *uart_send_buffer;
uint16_t uart_send_len;
TUYA_BLE_LOG_HEXDUMP_DEBUG("received uart cmd data", (uint8_t *)evt->uart_cmd_data.p_data, evt->uart_cmd_data.data_len); //
#if (TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
if (evt->uart_cmd_data.data_len > 0) {
sum = tuya_ble_check_sum(evt->uart_cmd_data.p_data, evt->uart_cmd_data.data_len - 1);
if (sum == evt->uart_cmd_data.p_data[evt->uart_cmd_data.data_len - 1]) {
switch (evt->uart_cmd_data.p_data[0]) {
case 0x55:
tuya_ble_uart_common_process(evt->uart_cmd_data.p_data, evt->uart_cmd_data.data_len);
break;
case 0x66:
tuya_ble_app_production_test_process(0, evt->uart_cmd_data.p_data, evt->uart_cmd_data.data_len);
break;
default:
break;
};
} else {
TUYA_BLE_LOG_ERROR("uart receive data check_sum error , receive sum = 0x%02x ; cal sum = 0x%02x", evt->uart_cmd_data.p_data[evt->uart_cmd_data.data_len - 1], sum);
}
}
#endif
if (evt->uart_cmd_data.p_data) {
tuya_ble_free(evt->uart_cmd_data.p_data);
}
}
void tuya_ble_handle_ble_cmd_evt(tuya_ble_evt_param_t *evt)
{
tuya_ble_evt_process(evt->ble_cmd_data.cmd, evt->ble_cmd_data.p_data, evt->ble_cmd_data.data_len);
if (evt->ble_cmd_data.p_data) {
tuya_ble_free(evt->ble_cmd_data.p_data);
}
}
void tuya_ble_handle_net_config_response_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
uint8_t data[2];
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_KEY_2;
} else {
encry_mode = ENCRYPTION_MODE_KEY_1;
}
data[0] = ((int16_t)(evt->net_config_response_data.result_code)) >> 8;
data[1] = (int16_t)(evt->net_config_response_data.result_code);
tuya_ble_commData_send(FRM_NET_CONFIG_RESPONSE_REPORT_REQ, 0, data, 2, encry_mode);
}
void tuya_ble_handle_time_request_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
uint16_t cmd;
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
if (evt->time_req_data.time_type == 0) {
cmd = FRM_GET_UNIX_TIME_CHAR_MS_REQ;
} else if (evt->time_req_data.time_type == 1) {
cmd = FRM_GET_UNIX_TIME_CHAR_DATE_REQ;
} else if (evt->time_req_data.time_type == 2) {
cmd = FRM_GET_APP_LOCAL_TIME_REQ;
} else {
return;
}
tuya_ble_commData_send(cmd, 0, NULL, 0, encry_mode);
}
void tuya_ble_handle_extend_time_request_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
uint8_t data[1];
if (tuya_ble_pair_rand_valid_get() == 1) {
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
} else {
encry_mode = ENCRYPTION_MODE_KEY_4;
}
data[0] = evt->extend_time_req_data.n_years_dst;
tuya_ble_commData_send(FRM_GET_UNIX_TIME_WITH_DST_REQ, 0, data, 1, encry_mode);
}
void tuya_ble_handle_unbound_response_evt(tuya_ble_evt_param_t *evt)
{
#if (!TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
uint8_t encry_mode = 0;
uint8_t result;
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
result = evt->ubound_res_data.result_code;
tuya_ble_commData_send(FRM_UNBONDING_RESP, 0, &result, 1, encry_mode);
#else
return;
#endif
}
void tuya_ble_handle_anomaly_unbound_response_evt(tuya_ble_evt_param_t *evt)
{
#if (!TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
uint8_t encry_mode = 0;
uint8_t result;
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
result = evt->anomaly_ubound_res_data.result_code;
tuya_ble_commData_send(FRM_ANOMALY_UNBONDING_RESP, 0, &result, 1, encry_mode);
#else
return;
#endif
}
void tuya_ble_handle_device_reset_response_evt(tuya_ble_evt_param_t *evt)
{
#if (!TUYA_BLE_DEVICE_REGISTER_FROM_BLE)
uint8_t encry_mode = 0;
uint8_t result;
encry_mode = ENCRYPTION_MODE_SESSION_KEY;
result = evt->device_reset_res_data.result_code;
tuya_ble_commData_send(FRM_DEVICE_RESET_RESP, 0, &result, 1, encry_mode);
#else
return;
#endif
}
#if (TUYA_BLE_PROTOCOL_VERSION_HIGN >= 3)
void tuya_ble_handle_connecting_request_evt(tuya_ble_evt_param_t *evt)
{
tuya_ble_connect_status_t currnet_connect_status;
currnet_connect_status = tuya_ble_connect_status_get();
if ((currnet_connect_status != BONDING_UNCONN) && (currnet_connect_status != UNBONDING_UNCONN)) {
return;
}
if (evt->connecting_request_data.cmd == 0) {
tuya_ble_adv_change();
} else {
tuya_ble_adv_change_with_connecting_request();
}
}
#endif
extern void tuya_ble_connect_monitor_timer_start(void);
void tuya_ble_handle_connect_change_evt(tuya_ble_evt_param_t *evt)
{
tuya_ble_cb_evt_param_t event;
uint8_t send_cb_flag = 1;
if (evt->connect_change_evt == TUYA_BLE_CONNECTED) {
TUYA_BLE_LOG_INFO("Connected!");
tuya_ble_reset_ble_sn();
if (tuya_ble_current_para.sys_settings.bound_flag != 1) {
tuya_ble_connect_status_set(UNBONDING_UNAUTH_CONN);
} else {
tuya_ble_connect_status_set(BONDING_UNAUTH_CONN);
}
tuya_ble_connect_monitor_timer_start();
#if (TUYA_BLE_DEVICE_REGISTER_FROM_BLE&&TUYA_BLE_DEVICE_AUTH_DATA_STORE)
tuya_ble_internal_production_test_with_ble_flag_clear();
#endif
#if (TUYA_BLE_SECURE_CONNECTION_TYPE==TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY_ADVANCED_ENCRYPTION)
tuya_ble_auth_data_reset();
#endif
#if TUYA_BLE_LINK_LAYER_ENCRYPTION_SUPPORT_ENABLE
tuya_ble_link_status_set(LINK_CONNECTED);
#endif
} else if (evt->connect_change_evt == TUYA_BLE_DISCONNECTED) {
TUYA_BLE_LOG_INFO("Disonnected");
tuya_ble_reset_ble_sn();
tuya_ble_pair_rand_clear();
tuya_ble_air_recv_packet_free();
if (tuya_ble_current_para.sys_settings.bound_flag == 1) {
tuya_ble_connect_status_set(BONDING_UNCONN);
} else {
tuya_ble_connect_status_set(UNBONDING_UNCONN);
}
#if TUYA_BLE_LINK_LAYER_ENCRYPTION_SUPPORT_ENABLE
tuya_ble_link_status_set(LINK_DISCONNECTED);
#endif
} else {
TUYA_BLE_LOG_WARNING("unknown connect_change_evt!");
}
if (send_cb_flag) {
event.evt = TUYA_BLE_CB_EVT_CONNECTE_STATUS;
event.connect_status = tuya_ble_connect_status_get();
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya ble send cb event failed.");
} else {
TUYA_BLE_LOG_DEBUG("tuya ble send cb event succeed.");
}
}
}
void tuya_ble_handle_link_update_evt(tuya_ble_evt_param_t *evt)
{
#if TUYA_BLE_LINK_LAYER_ENCRYPTION_SUPPORT_ENABLE
if (evt->link_update_data.link_app_status == 1) {
tuya_ble_link_status_set(LINK_ENCRYPTED);
if (tuya_ble_connect_status_get() != BONDING_CONN) {
tuya_ble_connect_monitor_timer_stop();
}
TUYA_BLE_LOG_DEBUG("link encrypted.");
}
#endif
}
void tuya_ble_handle_ble_data_evt(uint8_t *buf, uint16_t len)
{
tuya_ble_commonData_rx_proc(buf, len);
if (len > 20) {
tuya_ble_free(buf);
}
}

View File

@ -1,193 +0,0 @@
/**
* \file tuya_ble_event_handler_weak.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_event_handler.h"
__TUYA_BLE_WEAK void tuya_ble_handle_device_info_update_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_reported_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_with_time_reported_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_with_time_string_reported_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_with_flag_reported_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_with_flag_and_time_reported_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_with_flag_and_time_string_reported_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_send_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_dp_data_with_time_send_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_device_unbind_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_factory_reset_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_ota_response_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_bulk_data_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_data_passthrough_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_data_prod_test_response_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_uart_cmd_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_ble_cmd_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_net_config_response_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_time_request_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_extend_time_request_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_unbound_response_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_anomaly_unbound_response_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_device_reset_response_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_connect_change_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_connecting_request_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_ble_data_evt(uint8_t *buf, uint16_t len)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_link_update_evt(tuya_ble_evt_param_t *evt)
{
}
__TUYA_BLE_WEAK void tuya_ble_handle_weather_data_request_evt(tuya_ble_evt_param_t *evt)
{
}

View File

@ -1,447 +0,0 @@
/**
* \file tuya_ble_feature_weather.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_main.h"
#include "tuya_ble_internal_config.h"
#include "tuya_ble_feature_weather.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_mutli_tsf_protocol.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_secure.h"
#include "tuya_ble_main.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_unix_time.h"
#include "tuya_ble_log.h"
#include "tuya_ble_gatt_send_queue.h"
#if ( (TUYA_BLE_PROTOCOL_VERSION_HIGN==4) && (TUYA_BLE_FEATURE_WEATHER_ENABLE != 0) )
/**@brief Weather key string. */
const char *weather_key[] = {
"w.temp",
"w.thigh",
"w.tlow",
"w.humidity",
"w.condition",
"w.pressure",
"w.realFeel",
"w.uvi",
"w.sunRise",
"w.sunSet",
"t.unix",
"t.local",
"w.windSpeed",
"w.windDir",
"w.windLevel",
"w.aqi",
"w.tips",
"w.rank",
"w.pm10",
"w.pm25",
"w.o3",
"w.no2",
"w.co",
"w.so2",
"w.conditionNum",
"w.data.", //**< w.data.n, n rang from [1-7]
};
static tuya_ble_weather_location_type_t cur_req_weather_location_type;
/**
* @brief Function for calculate weather key max string length
*
* @return The max string len
*
* */
static uint16_t calc_weather_key_max_string_len(void)
{
int i, string_array_element = sizeof(weather_key) / sizeof(weather_key[0]);
uint16_t string_len = 0, tmp;
for (i = 0; i < string_array_element; i++) {
tmp = strlen(weather_key[i]);
if (tmp > string_len) {
string_len = tmp;
}
}
return string_len;
}
/**
* @brief Function for convert weather key to enum type
*
* @note For example input key "w.temp.0", convert type=WKT_TEMP day=1
*
* @param[in] key The ponit of input weather key string
* @param[out] type Convert type
* @param[out] day The day of weather data, rang from [1-7], 1-means today
*
* @retval TUYA_BLE_ERR_INVALID_PARAM The provided Parameters are not valid.
* @retval TUYA_BLE_ERR_NOT_FOUND No corresponding key was found.
* @retval TUYA_BLE_SUCCESS Successful.
*
* */
static tuya_ble_status_t weather_key_string_to_enum_type(char *key, uint8_t key_str_len, tuya_ble_weather_key_type_t *type, uint8_t *day)
{
int i, string_array_element;
if (key == NULL) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
string_array_element = sizeof(weather_key) / sizeof(weather_key[0]);
for (i = 0; i < string_array_element; i++) {
if ((strncmp(key, weather_key[i], strlen(weather_key[i])) == 0) && \
(key_str_len <= (strlen(weather_key[i]) + 2))) {
if (type != NULL) {
*type = (tuya_ble_weather_key_type_t)(1 << i);
}
if (day != NULL) {
if (key_str_len > strlen(weather_key[i])) {
/* key.n */
*day = key[strlen(weather_key[i]) + 1] - '0' + 1;
} else {
/* only today */
*day = 1;
}
}
return TUYA_BLE_SUCCESS;
}
}
return TUYA_BLE_ERR_NOT_FOUND;
}
tuya_ble_status_t tuya_ble_feature_weather_key_enum_type_to_string(tuya_ble_weather_key_type_t type, char *key)
{
int bit;
if (type >= WKT_COMBINE_BITMAP_MAXVAL || key == NULL) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
/* Convert to actual weather key string based on type */
for (bit = 0; bit < SUPPORT_WEATHER_KEY_TYPE_MAX_NUMS; bit++) {
if (((type >> bit) & 0x01) == 0x01) {
memcpy(key, weather_key[bit], strlen(weather_key[bit]));
return TUYA_BLE_SUCCESS;
}
}
return TUYA_BLE_ERR_NOT_FOUND;
}
/**
* @brief Function for parse weather lktlv format data
*
* @param[in] recv_data The point of input data
* @param[in] recv_len The length of input data
*
* @retval TUYA_BLE_ERR_INVALID_PARAM The provided Parameters are not valid.
* @retval TUYA_BLE_SUCCESS Successful.
*
* */
static tuya_ble_status_t weather_data_lktlv_parse(uint8_t *in, uint16_t in_len, uint8_t *out, uint16_t *out_len, uint16_t *object_nums)
{
uint8_t key_len, value_len, n_day;
uint16_t object_len = 0;
tuya_ble_weather_key_type_t weather_type;
tuya_ble_weather_value_type_t value_type;
tuya_ble_wd_object_t *object;
uint16_t tmp_out_len = 0, tmp_object_nums = 0;
if (in == NULL || in_len == 0 || out == NULL || out_len == NULL || object_nums == NULL) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
/*-------------------------------------------------------------------------
| 1byte | key_len | 1byte | 1byte | value_len |
| key_len | key | value_type | value_len | value |
---------------------------------------------------------------------------*/
for (;;) {
key_len = in[0 + object_len];
value_type = in[1 + key_len + object_len];
value_len = in[2 + key_len + object_len];
if (weather_key_string_to_enum_type((char *)&in[1 + object_len], key_len, &weather_type, &n_day) != TUYA_BLE_SUCCESS) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
TUYA_BLE_LOG_DEBUG("parse weather data, n_day=[%d] type=[0x%08x] val_type=[%d] ,", n_day, weather_type, value_type);
TUYA_BLE_LOG_HEXDUMP_DEBUG("value :", &in[3 + key_len + object_len], value_len);
/* Convert lktlv format to tuya_ble_wd_object */
object = (tuya_ble_wd_object_t *)tuya_ble_malloc(sizeof(tuya_ble_wd_object_t) + value_len);
if (object == NULL) {
return TUYA_BLE_ERR_NO_MEM;
}
object->n_day = n_day;
object->key_type = weather_type;
object->val_type = value_type;
object->value_len = value_len;
memcpy(&(object->vaule), &in[3 + key_len + object_len], value_len);
memcpy(&out[tmp_out_len], object, (sizeof(tuya_ble_wd_object_t) + value_len));
tmp_out_len += (sizeof(tuya_ble_wd_object_t) + value_len);
tuya_ble_free((uint8_t *)object);
tmp_object_nums += 1;
object_len += (key_len + value_len + 3);
if (object_len >= in_len) {
*out_len = tmp_out_len;
*object_nums = tmp_object_nums;
break;
}
}
TUYA_BLE_LOG_DEBUG("parse weather data finish, total count=[%d]", tmp_object_nums);
return TUYA_BLE_SUCCESS;
}
tuya_ble_status_t tuya_ble_feature_weather_data_request_with_location(tuya_ble_weather_location_type_t location_type, uint32_t combine_type, uint8_t n_days)
{
tuya_ble_evt_param_t event;
uint8_t *ble_evt_buffer = NULL;
uint16_t ble_evt_buffer_len = 0;
uint16_t per_weather_key_malloc_size, weather_key_len;
int bit, count;
if ((location_type >= WLT_MAX) || (location_type == WLT_CUSTOM_LOCATION)) {
TUYA_BLE_LOG_ERROR("request weather location type this sdk version unsupport");
return TUYA_BLE_ERR_INVALID_PARAM;
}
if (combine_type >= WKT_COMBINE_BITMAP_MAXVAL || n_days < 1 || n_days > 7) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
/* Calc total bit1 counters */
count = tuya_ble_count_bits((uint32_t)(combine_type));
if (0 == count) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
/* Malloc data buffer */
count += 1; // add w.data.n
per_weather_key_malloc_size = (calc_weather_key_max_string_len() + 4);
ble_evt_buffer = (uint8_t *)tuya_ble_malloc(2 + per_weather_key_malloc_size * count);
if (ble_evt_buffer == NULL) {
return TUYA_BLE_ERR_NO_MEM;
}
/* Fill version & location info */
cur_req_weather_location_type = location_type;
ble_evt_buffer[0] = 0;
ble_evt_buffer[1] = (uint8_t)(location_type);
ble_evt_buffer_len += 2;
/* Convert to actual weather key based on type */
for (bit = 0; bit < SUPPORT_WEATHER_KEY_TYPE_MAX_NUMS; bit++) {
if (((combine_type >> bit) & 0x01) == 0x01) {
/* Weather data format: [len + key] */
weather_key_len = strlen(weather_key[bit]);
ble_evt_buffer[ble_evt_buffer_len] = weather_key_len;
memcpy(&ble_evt_buffer[ble_evt_buffer_len + 1], weather_key[bit], weather_key_len);
ble_evt_buffer_len += (1 + weather_key_len);
}
}
/* Fill request n_days */
weather_key_len = sprintf((char *)&ble_evt_buffer[ble_evt_buffer_len + 1], "w.date.%d", n_days);
ble_evt_buffer[ble_evt_buffer_len] = weather_key_len;
ble_evt_buffer_len += (1 + weather_key_len);
TUYA_BLE_LOG_DEBUG("request weather location=[%d] type=[0x%x], n_days=[%d]", location_type, combine_type, n_days);
TUYA_BLE_LOG_HEXDUMP_DEBUG("request weather data :", ble_evt_buffer, ble_evt_buffer_len);
event.hdr.event = TUYA_BLE_EVT_WEATHER_DATA_REQ;
event.weather_req_data.p_data = ble_evt_buffer;
event.weather_req_data.data_len = ble_evt_buffer_len;
if (tuya_ble_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_event_send weather req data error");
tuya_ble_free(ble_evt_buffer);
return TUYA_BLE_ERR_NO_EVENT;
}
return TUYA_BLE_SUCCESS;
}
tuya_ble_status_t tuya_ble_feature_weather_data_request(uint32_t combine_type, uint8_t n_days)
{
return tuya_ble_feature_weather_data_request_with_location(WLT_APP_CURRENT_LOCATION, combine_type, n_days);
}
void tuya_ble_handle_weather_data_request_evt(tuya_ble_evt_param_t *evt)
{
uint8_t encry_mode = 0;
encry_mode = (tuya_ble_pair_rand_valid_get()) ? (ENCRYPTION_MODE_SESSION_KEY) : (ENCRYPTION_MODE_KEY_4);
tuya_ble_commData_send(FRM_WEATHER_DATA_REQUEST, 0, evt->weather_req_data.p_data, evt->weather_req_data.data_len, encry_mode);
if (evt->weather_req_data.p_data) {
tuya_ble_free(evt->weather_req_data.p_data);
}
}
void tuya_ble_handle_weather_data_request_response(uint8_t *recv_data, uint16_t recv_len)
{
tuya_ble_cb_evt_param_t event;
uint16_t data_len = recv_data[11] << 8 | recv_data[12];
if (data_len != 1) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_weather_data_request_response- invalid data len received.");
return;
}
event.evt = TUYA_BLE_CB_EVT_WEATHER_DATA_REQ_RESPONSE;
event.weather_req_response_data.status = recv_data[13];
if (tuya_ble_cb_event_send(&event) != 0) {
TUYA_BLE_LOG_ERROR("tuya_ble_handle_weather_data_request_response-tuya ble send cb event failed.");
} else {
}
}
void tuya_ble_handle_weather_data_received(uint8_t *recv_data, uint16_t recv_len)
{
uint8_t p_buf[1];
uint16_t data_len = 0;
uint32_t ack_sn = 0;
tuya_ble_cb_evt_param_t event;
uint16_t weather_data_start_pos, weather_data_len;
uint16_t buffer_len, object_count;
ack_sn = recv_data[1] << 24;
ack_sn += recv_data[2] << 16;
ack_sn += recv_data[3] << 8;
ack_sn += recv_data[4];
data_len = (recv_data[11] << 8) | recv_data[12];
if ((data_len < 5) || (data_len > TUYA_BLE_RECEIVE_MAX_DATA_LEN)) {
TUYA_BLE_LOG_ERROR("cmd weather data write error,receive data len == %d", data_len);
p_buf[0] = 0x01;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
return;
} else if (recv_data[13] != 0x00) {
TUYA_BLE_LOG_ERROR("cmd weather data write error, version not support");
p_buf[0] = 0x01;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
return;
} else if ((recv_data[14] >= WLT_MAX) || (recv_data[14] == WLT_CUSTOM_LOCATION)) {
TUYA_BLE_LOG_ERROR("cmd weather data write error, location type this sdk version unsupport");
p_buf[0] = 0x01;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
return;
} else if (recv_data[14] != cur_req_weather_location_type) {
TUYA_BLE_LOG_ERROR("cmd weather data write error, location type no correspondence");
p_buf[0] = 0x01;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
return;
}
TUYA_BLE_LOG_HEXDUMP_DEBUG("cmd weather data write : ", recv_data + 13, data_len);
/* parse location info */
weather_data_start_pos = 15;
weather_data_len = (data_len - 2);
uint8_t *ble_cb_evt_buffer = (uint8_t *)tuya_ble_malloc(weather_data_len);
if (ble_cb_evt_buffer == NULL) {
TUYA_BLE_LOG_ERROR("ble_cb_evt_buffer malloc failed.");
p_buf[0] = 0x01;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
return;
}
if (weather_data_lktlv_parse(&recv_data[weather_data_start_pos], weather_data_len, ble_cb_evt_buffer, &buffer_len, &object_count) != TUYA_BLE_SUCCESS) {
tuya_ble_free(ble_cb_evt_buffer);
TUYA_BLE_LOG_ERROR("cmd weather data parse failed");
p_buf[0] = 0x01;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
return;
}
event.evt = TUYA_BLE_CB_EVT_WEATHER_DATA_RECEIVED;
event.weather_received_data.object_count = object_count;
event.weather_received_data.location = recv_data[14];
event.weather_received_data.p_data = ble_cb_evt_buffer;
event.weather_received_data.data_len = buffer_len;
if (tuya_ble_cb_event_send(&event) != 0) {
tuya_ble_free(ble_cb_evt_buffer);
TUYA_BLE_LOG_ERROR("tuya_ble_handle_weather_data_received-tuya ble send cb event failed.");
p_buf[0] = 0x01;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
} else {
p_buf[0] = 0x00;
tuya_ble_commData_send(FRM_WEATHER_DATA_RECEIVED_RESP, ack_sn, p_buf, 1, ENCRYPTION_MODE_SESSION_KEY);
}
}
#else
void tuya_ble_handle_weather_data_request_evt(tuya_ble_evt_param_t *evt)
{
}
void tuya_ble_handle_weather_data_request_response(uint8_t *recv_data, uint16_t recv_len)
{
}
void tuya_ble_handle_weather_data_received(uint8_t *recv_data, uint16_t recv_len)
{
}
#endif

View File

@ -1,125 +0,0 @@
/**
* \file tuya_ble_gatt_send_queue.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_gatt_send_queue.h"
#include "tuya_ble_type.h"
#include "tuya_ble_config.h"
#include "tuya_ble_port.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_main.h"
#include "tuya_ble_log.h"
static tuya_ble_queue_t gatt_send_queue;
static tuya_ble_gatt_send_data_t send_buf[TUYA_BLE_GATT_SEND_DATA_QUEUE_SIZE];
static volatile uint8_t gatt_queue_flag = 0;
void tuya_ble_gatt_send_queue_init(void)
{
gatt_queue_flag = 0;
tuya_ble_queue_init(&gatt_send_queue, (void *) send_buf, TUYA_BLE_GATT_SEND_DATA_QUEUE_SIZE, sizeof(tuya_ble_gatt_send_data_t));
}
static void tuya_ble_gatt_send_queue_free(void)
{
tuya_ble_gatt_send_data_t data = {0};
memset(&data, 0, sizeof(tuya_ble_gatt_send_data_t));
while (tuya_ble_dequeue(&gatt_send_queue, &data) == TUYA_BLE_SUCCESS) {
if (data.buf) {
tuya_ble_free(data.buf);
}
memset(&data, 0, sizeof(tuya_ble_gatt_send_data_t));
}
TUYA_BLE_LOG_DEBUG("tuya_ble_gatt_send_queue_free execute.");
}
void tuya_ble_gatt_send_data_handle(void *evt)
{
tuya_ble_gatt_send_data_t data = {0};
tuya_ble_evt_param_t event;
tuya_ble_connect_status_t currnet_connect_status;
while (tuya_ble_queue_get(&gatt_send_queue, &data) == TUYA_BLE_SUCCESS) {
currnet_connect_status = tuya_ble_connect_status_get();
if ((currnet_connect_status == BONDING_UNCONN) || (currnet_connect_status == UNBONDING_UNCONN)) {
tuya_ble_gatt_send_queue_free();
break;
}
if (tuya_ble_gatt_send_data(data.buf, data.size) == TUYA_BLE_SUCCESS) {
tuya_ble_free(data.buf);
tuya_ble_queue_decrease(&gatt_send_queue);
} else {
event.hdr.event = TUYA_BLE_EVT_GATT_SEND_DATA;
event.hdr.event_handler = tuya_ble_gatt_send_data_handle;
if (tuya_ble_event_send(&event) != 0) {
tuya_ble_gatt_send_queue_free();
TUYA_BLE_LOG_ERROR("TUYA_BLE_EVT_GATT_SEND_DATA error.");
}
break;
}
}
if (tuya_ble_get_queue_used(&gatt_send_queue) == 0) {
tuya_ble_queue_flush(&gatt_send_queue);
gatt_queue_flag = 0;
}
}
tuya_ble_status_t tuya_ble_gatt_send_data_enqueue(uint8_t *p_data, uint8_t data_len)
{
tuya_ble_gatt_send_data_t data = {0};
data.buf = tuya_ble_malloc(data_len);
if (data.buf) {
memcpy(data.buf, p_data, data_len);
data.size = data_len;
if (tuya_ble_enqueue(&gatt_send_queue, &data) == TUYA_BLE_SUCCESS) {
if (gatt_queue_flag == 0) {
gatt_queue_flag = 1;
tuya_ble_gatt_send_data_handle(NULL);
}
return TUYA_BLE_SUCCESS;
} else {
tuya_ble_free(data.buf);
return TUYA_BLE_ERR_NO_MEM;
}
} else {
return TUYA_BLE_ERR_NO_MEM;
}
}
uint32_t tuya_ble_get_gatt_send_queue_used(void)
{
return tuya_ble_get_queue_used(&gatt_send_queue);
}

View File

@ -1,366 +0,0 @@
/*
* FreeRTOS Kernel V10.0.0
* Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software. If you wish to use our Amazon
* FreeRTOS name, please do so in a fair use way that does not cause confusion.
*
* 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.
*
* http://www.FreeRTOS.org
* http://aws.amazon.com/freertos
*
* 1 tab == 4 spaces!
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_port.h"
#include "tuya_ble_internal_config.h"
#if (TUYA_BLE_USE_PLATFORM_MEMORY_HEAP==0)
/* Block sizes must not get too small. */
#define heapMINIMUM_BLOCK_SIZE ( ( uint32_t ) ( xHeapStructSize << 1 ) )
/* Assumes 8bit bytes! */
#define heapBITS_PER_BYTE ( ( uint32_t ) 8 )
static uint8_t ucHeap[ TUYA_BLE_TOTAL_HEAP_SIZE ];
/* Define the linked list structure. This is used to link free blocks in order
of their memory address. */
typedef struct A_BLOCK_LINK {
struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */
uint32_t xBlockSize; /*<< The size of the free block. */
} BlockLink_t;
/*-----------------------------------------------------------*/
/*
* Inserts a block of memory that is being freed into the correct position in
* the list of free memory blocks. The block being freed will be merged with
* the block in front it and/or the block behind it if the memory blocks are
* adjacent to each other.
*/
static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert);
/*
* Called automatically to setup the required heap structures the first time
* pvPortMalloc() is called.
*/
static void prvHeapInit(void);
/*-----------------------------------------------------------*/
/* The size of the structure placed at the beginning of each allocated memory
block must by correctly byte aligned. */
static const uint32_t xHeapStructSize = (sizeof(BlockLink_t) + ((uint32_t)(portBYTE_ALIGNMENT - 1))) & ~((uint32_t) portBYTE_ALIGNMENT_MASK);
/* Create a couple of list links to mark the start and end of the list. */
static BlockLink_t xStart, *pxEnd = NULL;
/* Keeps track of the number of free bytes remaining, but says nothing about
fragmentation. */
static uint32_t xFreeBytesRemaining = 0U;
static uint32_t xMinimumEverFreeBytesRemaining = 0U;
/* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
member of an BlockLink_t structure is set then the block belongs to the
application. When the bit is free the block is still part of the free heap
space. */
static uint32_t xBlockAllocatedBit = 0;
/*-----------------------------------------------------------*/
void *pvTuyaPortMalloc(uint32_t xWantedSize)
{
BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
void *pvReturn = NULL;
tuya_ble_device_enter_critical();
{
/* If this is the first call to malloc then the heap will require
initialisation to setup the list of free blocks. */
if (pxEnd == NULL) {
prvHeapInit();
} else {
tuyaCOVERAGE_TEST_MARKER();
}
/* Check the requested block size is not so large that the top bit is
set. The top bit of the block size member of the BlockLink_t structure
is used to determine who owns the block - the application or the
kernel, so it must be free. */
if ((xWantedSize & xBlockAllocatedBit) == 0) {
/* The wanted size is increased so it can contain a BlockLink_t
structure in addition to the requested amount of bytes. */
if (xWantedSize > 0) {
xWantedSize += xHeapStructSize;
/* Ensure that blocks are always aligned to the required number
of bytes. */
if ((xWantedSize & portBYTE_ALIGNMENT_MASK) != 0x00) {
/* Byte alignment required. */
xWantedSize += (portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK));
tuyaASSERT((xWantedSize & portBYTE_ALIGNMENT_MASK) == 0);
} else {
tuyaCOVERAGE_TEST_MARKER();
}
} else {
tuyaCOVERAGE_TEST_MARKER();
}
if ((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining)) {
/* Traverse the list from the start (lowest address) block until
one of adequate size is found. */
pxPreviousBlock = &xStart;
pxBlock = xStart.pxNextFreeBlock;
while ((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL)) {
pxPreviousBlock = pxBlock;
pxBlock = pxBlock->pxNextFreeBlock;
}
/* If the end marker was reached then a block of adequate size
was not found. */
if (pxBlock != pxEnd) {
/* Return the memory space pointed to - jumping over the
BlockLink_t structure at its start. */
pvReturn = (void *)(((uint8_t *) pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize);
/* This block is being returned for use so must be taken out
of the list of free blocks. */
pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
/* If the block is larger than required it can be split into
two. */
if ((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE) {
/* This block is to be split into two. Create a new
block following the number of bytes requested. The void
cast is used to prevent byte alignment warnings from the
compiler. */
pxNewBlockLink = (void *)(((uint8_t *) pxBlock) + xWantedSize);
tuyaASSERT((((uint32_t) pxNewBlockLink) & portBYTE_ALIGNMENT_MASK) == 0);
/* Calculate the sizes of two blocks split from the
single block. */
pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
pxBlock->xBlockSize = xWantedSize;
/* Insert the new block into the list of free blocks. */
prvInsertBlockIntoFreeList(pxNewBlockLink);
} else {
tuyaCOVERAGE_TEST_MARKER();
}
xFreeBytesRemaining -= pxBlock->xBlockSize;
if (xFreeBytesRemaining < xMinimumEverFreeBytesRemaining) {
xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
} else {
tuyaCOVERAGE_TEST_MARKER();
}
/* The block is being returned - it is allocated and owned
by the application and has no "next" block. */
pxBlock->xBlockSize |= xBlockAllocatedBit;
pxBlock->pxNextFreeBlock = NULL;
} else {
tuyaCOVERAGE_TEST_MARKER();
}
} else {
tuyaCOVERAGE_TEST_MARKER();
}
} else {
tuyaCOVERAGE_TEST_MARKER();
}
tuya_traceMALLOC(pvReturn, xWantedSize);
}
(void) tuya_ble_device_exit_critical();
#if( tuyaUSE_MALLOC_FAILED_HOOK == 1 )
{
if (pvReturn == NULL) {
extern void vApplicationMallocFailedHook(void);
vApplicationMallocFailedHook();
} else {
tuyaCOVERAGE_TEST_MARKER();
}
}
#endif
tuyaASSERT((((uint32_t) pvReturn) & (uint32_t) portBYTE_ALIGNMENT_MASK) == 0);
return pvReturn;
}
/*-----------------------------------------------------------*/
void vTuyaPortFree(void *pv)
{
uint8_t *puc = (uint8_t *) pv;
BlockLink_t *pxLink;
if (pv != NULL) {
/* The memory being freed will have an BlockLink_t structure immediately
before it. */
puc -= xHeapStructSize;
/* This casting is to keep the compiler from issuing warnings. */
pxLink = (void *) puc;
/* Check the block is actually allocated. */
tuyaASSERT((pxLink->xBlockSize & xBlockAllocatedBit) != 0);
tuyaASSERT(pxLink->pxNextFreeBlock == NULL);
if ((pxLink->xBlockSize & xBlockAllocatedBit) != 0) {
if (pxLink->pxNextFreeBlock == NULL) {
/* The block is being returned to the heap - it is no longer
allocated. */
pxLink->xBlockSize &= ~xBlockAllocatedBit;
tuya_ble_device_enter_critical();
{
/* Add this block to the list of free blocks. */
xFreeBytesRemaining += pxLink->xBlockSize;
tuya_traceFREE(pv, pxLink->xBlockSize);
prvInsertBlockIntoFreeList(((BlockLink_t *) pxLink));
}
(void) tuya_ble_device_exit_critical();
} else {
tuyaCOVERAGE_TEST_MARKER();
}
} else {
tuyaCOVERAGE_TEST_MARKER();
}
}
}
/*-----------------------------------------------------------*/
uint32_t xTuyaPortGetFreeHeapSize(void)
{
return xFreeBytesRemaining;
}
/*-----------------------------------------------------------*/
uint32_t xTuyaPortGetMinimumEverFreeHeapSize(void)
{
return xMinimumEverFreeBytesRemaining;
}
/*-----------------------------------------------------------*/
void vTuyaPortInitialiseBlocks(void)
{
/* This just exists to keep the linker quiet. */
}
/*-----------------------------------------------------------*/
static void prvHeapInit(void)
{
BlockLink_t *pxFirstFreeBlock;
uint8_t *pucAlignedHeap;
uint32_t uxAddress;
uint32_t xTotalHeapSize = TUYA_BLE_TOTAL_HEAP_SIZE;
/* Ensure the heap starts on a correctly aligned boundary. */
uxAddress = (uint32_t) ucHeap;
if ((uxAddress & portBYTE_ALIGNMENT_MASK) != 0) {
uxAddress += (portBYTE_ALIGNMENT - 1);
uxAddress &= ~((uint32_t) portBYTE_ALIGNMENT_MASK);
xTotalHeapSize -= uxAddress - (uint32_t) ucHeap;
}
pucAlignedHeap = (uint8_t *) uxAddress;
/* xStart is used to hold a pointer to the first item in the list of free
blocks. The void cast is used to prevent compiler warnings. */
xStart.pxNextFreeBlock = (void *) pucAlignedHeap;
xStart.xBlockSize = (uint32_t) 0;
/* pxEnd is used to mark the end of the list of free blocks and is inserted
at the end of the heap space. */
uxAddress = ((uint32_t) pucAlignedHeap) + xTotalHeapSize;
uxAddress -= xHeapStructSize;
uxAddress &= ~((uint32_t) portBYTE_ALIGNMENT_MASK);
pxEnd = (void *) uxAddress;
pxEnd->xBlockSize = 0;
pxEnd->pxNextFreeBlock = NULL;
/* To start with there is a single free block that is sized to take up the
entire heap space, minus the space taken by pxEnd. */
pxFirstFreeBlock = (void *) pucAlignedHeap;
pxFirstFreeBlock->xBlockSize = uxAddress - (uint32_t) pxFirstFreeBlock;
pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
/* Only one block exists - and it covers the entire usable heap space. */
xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
/* Work out the position of the top bit in a size_t variable. */
xBlockAllocatedBit = ((uint32_t) 1) << ((sizeof(uint32_t) * heapBITS_PER_BYTE) - 1);
}
/*-----------------------------------------------------------*/
static void prvInsertBlockIntoFreeList(BlockLink_t *pxBlockToInsert)
{
BlockLink_t *pxIterator;
uint8_t *puc;
/* Iterate through the list until a block is found that has a higher address
than the block being inserted. */
for (pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock) {
/* Nothing to do here, just iterate to the right position. */
}
/* Do the block being inserted, and the block it is being inserted after
make a contiguous block of memory? */
puc = (uint8_t *) pxIterator;
if ((puc + pxIterator->xBlockSize) == (uint8_t *) pxBlockToInsert) {
pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
pxBlockToInsert = pxIterator;
} else {
tuyaCOVERAGE_TEST_MARKER();
}
/* Do the block being inserted, and the block it is being inserted before
make a contiguous block of memory? */
puc = (uint8_t *) pxBlockToInsert;
if ((puc + pxBlockToInsert->xBlockSize) == (uint8_t *) pxIterator->pxNextFreeBlock) {
if (pxIterator->pxNextFreeBlock != pxEnd) {
/* Form one big block from the two blocks. */
pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
} else {
pxBlockToInsert->pxNextFreeBlock = pxEnd;
}
} else {
pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
}
/* If the block being inserted plugged a gab, so was merged with the block
before and the block after, then it's pxNextFreeBlock pointer will have
already been set, and should not be set here as that would make it point
to itself. */
if (pxIterator != pxBlockToInsert) {
pxIterator->pxNextFreeBlock = pxBlockToInsert;
} else {
tuyaCOVERAGE_TEST_MARKER();
}
}
#endif

View File

@ -1,140 +0,0 @@
/**
* \file tuya_ble_mem.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_heap.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_internal_config.h"
#if (TUYA_BLE_USE_PLATFORM_MEMORY_HEAP==0)
/**
*@brief Allocate and clear a memory block with required size.
*@param[in] size Required memory size.
*
*@note
*
* */
void *tuya_ble_malloc(uint16_t size)
{
uint8_t *ptr = pvTuyaPortMalloc(size);
if (ptr) {
memset(ptr, 0x0, size); //allocate buffer need init
}
return ptr;
}
/**
*@brief Free a memory block that had been allocated.
*@param[in] ptr The address of memory block being freed.
*
*@note
*
* */
tuya_ble_status_t tuya_ble_free(uint8_t *ptr)
{
if (ptr == NULL) {
return TUYA_BLE_SUCCESS;
}
vTuyaPortFree(ptr);
return TUYA_BLE_SUCCESS;
}
/**
*@brief
*@param
*
*@note
*
* */
void *tuya_ble_calloc_n(uint32_t n, uint32_t size)
{
void *ptr = NULL;
ptr = pvTuyaPortMalloc(n * size);
if (ptr != NULL) {
memset(ptr, 0, n * size);
}
return ptr;
}
/**
*@brief
*@param
*
*@note
*
* */
void tuya_ble_free_n(void *ptr)
{
vTuyaPortFree(ptr);
}
#else
/**
*@brief Allocate and clear a memory block with required size.
*@param[in] size Required memory size.
*
*@note
*
* */
void *tuya_ble_malloc(uint16_t size)
{
uint8_t *ptr = tuya_ble_port_malloc(size);
if (ptr) {
memset(ptr, 0x0, size); //allocate buffer need init
}
return ptr;
}
/**
*@brief Free a memory block that had been allocated.
*@param[in] ptr The address of memory block being freed.
*
*@note
*
* */
tuya_ble_status_t tuya_ble_free(uint8_t *ptr)
{
if (ptr == NULL) {
return TUYA_BLE_SUCCESS;
}
tuya_ble_port_free(ptr);
return TUYA_BLE_SUCCESS;
}
#endif

View File

@ -1,710 +0,0 @@
/**
* \file tuya_ble_mutli_tsf_protocol.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_type.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_mutli_tsf_protocol.h"
#define __MUTLI_TSF_PROTOCOL_GLOBALS
/***********************************************************
*************************micro define***********************
***********************************************************/
#define MTP_DEBUG 1
#if MTP_DEBUG
#define MTP_PR_DEBUG(_fmt_, ...) \
printf("[mtp:dbg]%s:%d "_fmt_"\n\r", __FILE__, __LINE__, ##__VA_ARGS__)
#define MTP_PR_DEBUG_RAW(_fmt_, ...) \
printf(_fmt_, ##__VA_ARGS__)
#else
#define MTP_PR_DEBUG(...)
#define MTP_PR_DEBUG_RAW(_fmt_, ...)
#endif
#define MTP_PR_NOTICE(_fmt_, ...) \
printf("[mtp:notice]%s:%d "_fmt_"\n\r", __FILE__, __LINE__, ##__VA_ARGS__)
#define MTP_PR_ERR(_fmt_, ...) \
printf("[mtp:err]%s:%d "_fmt_"\n\r", __FILE__, __LINE__, ##__VA_ARGS__)
#undef NULL
#define NULL (void *)0
/***********************************************************
*************************variable define********************
***********************************************************/
static frame_seq_t frame_seq = 0;
/***********************************************************
*************************function define********************
***********************************************************/
/***********************************************************
* Function: create_trsmitr_init
* description: create a transmitter and initialize
* Input: none
* Output:
* Return: transmitter handle
***********************************************************/
frm_trsmitr_proc_s *create_trsmitr_init(void)
{
frm_trsmitr_proc_s *frm_trsmitr = NULL;
frm_trsmitr = (frm_trsmitr_proc_s *)tuya_ble_malloc(sizeof(frm_trsmitr_proc_s));
if ((void *)0 == frm_trsmitr) {
return (void *)0;
}
memset(frm_trsmitr, 0, sizeof(frm_trsmitr_proc_s));
return frm_trsmitr;
}
/***********************************************************
* Function: trsmitr_init
* description: init a transmitter
* Input: transmitter handle
* Output:
* Return:
***********************************************************/
void trsmitr_init(frm_trsmitr_proc_s *frm_trsmitr)
{
memset(frm_trsmitr, 0, sizeof(frm_trsmitr_proc_s));
}
/***********************************************************
* Function: delete_trsmitr
* description: delete transmitter
* Input: transmitter handle
* Output:
* Return:
***********************************************************/
void delete_trsmitr(frm_trsmitr_proc_s *frm_trsmitr)
{
//free(frm_trsmitr);
tuya_ble_free((uint8_t *)frm_trsmitr);
}
/***********************************************************
* Function: get_trsmitr_frame_total_len
* description: get a transmitter total data len
* Input: transmitter handle
* Output:
* Return: frame_total_t
***********************************************************/
frame_total_t get_trsmitr_frame_total_len(frm_trsmitr_proc_s *frm_trsmitr)
{
return frm_trsmitr->total;
}
/***********************************************************
* Function: get_trsmitr_frame_version
* description:
* Input: transmitter handle
* Output:
* Return:
***********************************************************/
uint8_t get_trsmitr_frame_version(frm_trsmitr_proc_s *frm_trsmitr)
{
return frm_trsmitr->version;
}
/***********************************************************
* Function: get_trsmitr_frame_seq
* description:
* Input: transmitter handle
* Output:
* Return: frame_seq_t
***********************************************************/
frame_seq_t get_trsmitr_frame_seq(frm_trsmitr_proc_s *frm_trsmitr)
{
return frm_trsmitr->seq;
}
/***********************************************************
* Function: get_trsmitr_subpkg_len
* description:
* Input: transmitter handle
* Output:
* Return: frame_subpkg_len_t
***********************************************************/
frame_subpkg_len_t get_trsmitr_subpkg_len(frm_trsmitr_proc_s *frm_trsmitr)
{
return frm_trsmitr->subpkg_len;
}
/***********************************************************
* Function: get_trsmitr_subpkg
* description:
* Input: transmitter handle
* Output:
* Return: subpackage buf
***********************************************************/
uint8_t *get_trsmitr_subpkg(frm_trsmitr_proc_s *frm_trsmitr)
{
return frm_trsmitr->subpkg;
}
static frame_seq_t get_frame_seq(void) //Because this type of data is not used temporarily, it can be used for multi-threaded calls temporarily
{
return (frame_seq >= FRAME_SEQ_LMT) ? 0 : frame_seq++;
}
/***********************************************************
* Function: trsmitr_send_pkg_encode
* description: frm_trsmitr->transmitter handle
* type->frame type
* buf->data buf
* len->data len
* Input:
* Output:
* Return: MTP_OK->buf send up
* MTP_TRSMITR_CONTINUE->need call again to be continue
* other->error
* Note: could get from encode data len and encode data by calling method
get_trsmitr_subpkg_len() and get_trsmitr_subpkg()
***********************************************************/
mtp_ret trsmitr_send_pkg_encode(frm_trsmitr_proc_s *frm_trsmitr, uint8_t version, uint8_t *buf, uint32_t len)
{
if (((void *)0) == frm_trsmitr) {
return MTP_INVALID_PARAM;
}
if (FRM_PKG_INIT == frm_trsmitr->pkg_desc) {
frm_trsmitr->total = len;
frm_trsmitr->version = version;
frm_trsmitr->seq = get_frame_seq();
frm_trsmitr->subpkg_num = 0;
frm_trsmitr->pkg_trsmitr_cnt = 0;
}
if (frm_trsmitr->subpkg_num >= 0x10000000 || len >= 0x10000000) {
return MTP_COM_ERROR;
}
uint16_t sunpkg_offset = 0;
// package code
// subpackage num encode
int32_t i;
uint32_t tmp = 0;
tmp = frm_trsmitr->subpkg_num;
for (i = 0; i < 4; i++) {
frm_trsmitr->subpkg[sunpkg_offset] = tmp % 0x80;
if ((tmp / 0x80)) {
frm_trsmitr->subpkg[sunpkg_offset] |= 0x80;
}
sunpkg_offset++;
tmp /= 0x80;
if (0 == tmp) {
break;
}
}
// the first package include the frame total len
if (0 == frm_trsmitr->subpkg_num) {
// frame len encode
tmp = len;
for (i = 0; i < 4; i++) {
frm_trsmitr->subpkg[sunpkg_offset] = tmp % 0x80;
if ((tmp / 0x80)) {
frm_trsmitr->subpkg[sunpkg_offset] |= 0x80;
}
sunpkg_offset++;
tmp /= 0x80;
if (0 == tmp) {
break;
}
}
// frame type and frame seq
frm_trsmitr->subpkg[sunpkg_offset++] = (frm_trsmitr->version << 0x04) | (frm_trsmitr->seq & 0x0f);
}
// frame data transfer
uint16_t send_data_len = (SNGL_PKG_TRSFR_LMT - sunpkg_offset);
if ((len - frm_trsmitr->pkg_trsmitr_cnt) < send_data_len) {
send_data_len = len - frm_trsmitr->pkg_trsmitr_cnt;
}
memcpy(&(frm_trsmitr->subpkg[sunpkg_offset]), buf + frm_trsmitr->pkg_trsmitr_cnt, send_data_len);
frm_trsmitr->subpkg_len = sunpkg_offset + send_data_len;
frm_trsmitr->pkg_trsmitr_cnt += send_data_len;
if (0 == frm_trsmitr->subpkg_num) {
frm_trsmitr->pkg_desc = FRM_PKG_FIRST;
} else {
frm_trsmitr->pkg_desc = FRM_PKG_MIDDLE;
}
if (frm_trsmitr->pkg_trsmitr_cnt < frm_trsmitr->total) {
frm_trsmitr->subpkg_num++;
return MTP_TRSMITR_CONTINUE;
}
frm_trsmitr->pkg_desc = FRM_PKG_END;
return MTP_OK;
}
/***********************************************************
* Function: trsmitr_send_pkg_encode_with_packet_length
* description: Encoding function for specifying sub-packet length
*
*
*
* Input:
* Output:
* Return: MTP_OK->buf send up
* MTP_TRSMITR_CONTINUE->need call again to be continue
* other->error
* Note: could get from encode data len and encode data by calling method
get_trsmitr_subpkg_len() and get_trsmitr_subpkg()
***********************************************************/
mtp_ret trsmitr_send_pkg_encode_with_packet_length(frm_trsmitr_proc_s *frm_trsmitr, uint32_t pkg_len_max, uint8_t version, uint8_t *buf, uint32_t len)
{
if (((void *)0) == frm_trsmitr) {
return MTP_INVALID_PARAM;
}
if ((pkg_len_max == 0) || (pkg_len_max > SNGL_PKG_TRSFR_LMT)) {
return MTP_INVALID_PARAM;
}
if (FRM_PKG_INIT == frm_trsmitr->pkg_desc) {
frm_trsmitr->total = len;
frm_trsmitr->version = version;
frm_trsmitr->seq = get_frame_seq();
frm_trsmitr->subpkg_num = 0;
frm_trsmitr->pkg_trsmitr_cnt = 0;
}
if (frm_trsmitr->subpkg_num >= 0x10000000 || len >= 0x10000000) {
return MTP_COM_ERROR;
}
uint16_t sunpkg_offset = 0;
// package code
// subpackage num encode
int32_t i;
uint32_t tmp = 0;
tmp = frm_trsmitr->subpkg_num;
for (i = 0; i < 4; i++) {
frm_trsmitr->subpkg[sunpkg_offset] = tmp % 0x80;
if ((tmp / 0x80)) {
frm_trsmitr->subpkg[sunpkg_offset] |= 0x80;
}
sunpkg_offset++;
tmp /= 0x80;
if (0 == tmp) {
break;
}
}
// the first package include the frame total len
if (0 == frm_trsmitr->subpkg_num) {
// frame len encode
tmp = len;
for (i = 0; i < 4; i++) {
frm_trsmitr->subpkg[sunpkg_offset] = tmp % 0x80;
if ((tmp / 0x80)) {
frm_trsmitr->subpkg[sunpkg_offset] |= 0x80;
}
sunpkg_offset++;
tmp /= 0x80;
if (0 == tmp) {
break;
}
}
// frame type and frame seq
frm_trsmitr->subpkg[sunpkg_offset++] = (frm_trsmitr->version << 0x04) | (frm_trsmitr->seq & 0x0f);
}
// frame data transfer
uint16_t send_data_len = (pkg_len_max - sunpkg_offset);
if ((len - frm_trsmitr->pkg_trsmitr_cnt) < send_data_len) {
send_data_len = len - frm_trsmitr->pkg_trsmitr_cnt;
}
memcpy(&(frm_trsmitr->subpkg[sunpkg_offset]), buf + frm_trsmitr->pkg_trsmitr_cnt, send_data_len);
frm_trsmitr->subpkg_len = sunpkg_offset + send_data_len;
frm_trsmitr->pkg_trsmitr_cnt += send_data_len;
if (0 == frm_trsmitr->subpkg_num) {
frm_trsmitr->pkg_desc = FRM_PKG_FIRST;
} else {
frm_trsmitr->pkg_desc = FRM_PKG_MIDDLE;
}
if (frm_trsmitr->pkg_trsmitr_cnt < frm_trsmitr->total) {
frm_trsmitr->subpkg_num++;
return MTP_TRSMITR_CONTINUE;
}
frm_trsmitr->pkg_desc = FRM_PKG_END;
return MTP_OK;
}
mtp_ret trsmitr_recv_pkg_decode(frm_trsmitr_proc_s *frm_trsmitr, uint8_t *raw_data, uint16_t raw_data_len)
{
if (NULL == raw_data || (raw_data_len > SNGL_PKG_TRSFR_LMT) || NULL == frm_trsmitr) {
return MTP_INVALID_PARAM;
}
if (FRM_PKG_INIT == frm_trsmitr->pkg_desc) {
frm_trsmitr->total = 0;
frm_trsmitr->version = 0;
frm_trsmitr->seq = 0;
frm_trsmitr->pkg_trsmitr_cnt = 0;
}
uint16_t sunpkg_offset = 0;
// package code
// subpackage num decode
int32_t i;
uint32_t multiplier = 1;
uint8_t digit;
frame_subpkg_num_t subpkg_num = 0;
//Package number
for (i = 0; i < 4; i++) {
digit = raw_data[sunpkg_offset++];
subpkg_num += (digit & 0x7f) * multiplier;
multiplier *= 0x80;
if (0 == (digit & 0x80)) {
break;
}
}
if (0 == subpkg_num) {
frm_trsmitr->total = 0;
frm_trsmitr->version = 0;
frm_trsmitr->seq = 0;
frm_trsmitr->pkg_trsmitr_cnt = 0;
frm_trsmitr->pkg_desc = FRM_PKG_FIRST;
} else {
frm_trsmitr->pkg_desc = FRM_PKG_MIDDLE;
}
if (frm_trsmitr->subpkg_num >= 0x10000000) {
return MTP_COM_ERROR;
}
// is receive the subpackage num valid?
if (frm_trsmitr->pkg_desc != FRM_PKG_FIRST) {
if (subpkg_num < frm_trsmitr->subpkg_num) {
return MTP_TRSMITR_ERROR;
} else if (subpkg_num == frm_trsmitr->subpkg_num) {
return MTP_TRSMITR_CONTINUE;
}
if (subpkg_num - frm_trsmitr->subpkg_num > 1) {
return MTP_TRSMITR_ERROR;
}
}
frm_trsmitr->subpkg_num = subpkg_num;
if (0 == frm_trsmitr->subpkg_num) {
// frame len decode
multiplier = 1;
for (i = 0; i < 4; i++) {
digit = raw_data[sunpkg_offset++];
frm_trsmitr->total += (digit & 0x7f) * multiplier;
multiplier *= 0x80;
if (0 == (digit & 0x80)) {
break;
}
}
if (frm_trsmitr->total >= 0x10000000) {
return MTP_COM_ERROR;
}
// frame type and frame seq decode
frm_trsmitr->version = (raw_data[sunpkg_offset] & FRM_VERSION_OFFSET) >> 4;
frm_trsmitr->seq = raw_data[sunpkg_offset++] & FRM_SEQ_OFFSET;
}
uint16_t recv_data_len = raw_data_len - sunpkg_offset;
if ((frm_trsmitr->total - frm_trsmitr->pkg_trsmitr_cnt) < recv_data_len) {
recv_data_len = frm_trsmitr->total - frm_trsmitr->pkg_trsmitr_cnt;
}
// decode data cp to transmitter subpackage buf
memcpy(frm_trsmitr->subpkg, &raw_data[sunpkg_offset], recv_data_len);
frm_trsmitr->subpkg_len = recv_data_len;
frm_trsmitr->pkg_trsmitr_cnt += recv_data_len;
if (frm_trsmitr->pkg_trsmitr_cnt < frm_trsmitr->total) {
return MTP_TRSMITR_CONTINUE;
}
//cannot add 'frm_trsmitr->pkg_desc = FRM_PKG_END;' here.
return MTP_OK;
}
/***********************************************************
* Function: free_klv_list
* description:
* Input: list
* Output:
* Return:
***********************************************************/
void free_klv_list(klv_node_s *list)
{
if (NULL == list) {
return;
}
klv_node_s *node = list;
klv_node_s *next_node = NULL;
do {
next_node = node->next;
//free(node);
tuya_ble_free((uint8_t *)(node->data));
tuya_ble_free((uint8_t *)node);
node = next_node;
} while (node);
}
/***********************************************************
* Function: make_klv_list
* description:
* Input:
* Output:
* Return:
***********************************************************/
klv_node_s *make_klv_list(klv_node_s *list, uint8_t id, dp_type type, void *p_data, uint16_t len)
{
klv_node_s *node = NULL;
uint32_t tmp4 = 0, tmp2 = 0;
if (NULL == p_data || type >= DT_LMT) {
return NULL;
}
if (DT_VALUE == type && DT_VALUE_LEN != len) {
goto err_ret;
} else if (DT_BITMAP == type && len != 1 && len != 2 && len != DT_BITMAP_MAX) {
goto err_ret;
} else if (DT_BOOL == type && DT_BOOL_LEN != len) {
goto err_ret;
} else if (DT_ENUM == type && DT_ENUM_LEN != len) {
goto err_ret;
}
node = (klv_node_s *)tuya_ble_malloc(sizeof(klv_node_s));
if (NULL == node) {
goto err_ret;
}
memset(node, 0, sizeof(klv_node_s));
if (len > 0) {
node->data = tuya_ble_malloc(len);
if (node->data == NULL) {
tuya_ble_free(node->data);
tuya_ble_free((uint8_t *)node);
goto err_ret;
}
}
node->id = id;
node->len = len;
node->type = type;
if (DT_VALUE == type) {
// change to big-end
tmp4 = *(uint32_t *)p_data;
// unsigned char shift = 0;
node->data[0] = (tmp4 >> 24) & 0xff;
node->data[1] = (tmp4 >> 16) & 0xff;
node->data[2] = (tmp4 >> 8) & 0xff;
node->data[3] = (tmp4 >> 0) & 0xff;
} else if (DT_BITMAP == type) {
if (len == 4) {
tmp4 = *(uint32_t *)p_data;
// unsigned char shift = 0;
node->data[0] = (tmp4 >> 24) & 0xff;
node->data[1] = (tmp4 >> 16) & 0xff;
node->data[2] = (tmp4 >> 8) & 0xff;
node->data[3] = (tmp4 >> 0) & 0xff;
} else if (len == 2) {
tmp2 = *(uint16_t *)p_data;
node->data[0] = (tmp2 >> 8) & 0xff;
node->data[1] = (tmp2 >> 0) & 0xff;
} else {
node->data[0] = *(uint8_t *)p_data;
}
} else {
if (len > 0) {
memcpy((void *)node->data, (uint8_t *)p_data, len);
}
}
node->next = list;
return node;
err_ret:
free_klv_list(list);
return NULL;
}
/***********************************************************
* Function: klvlist_2_data
* description:
* Input: type:0- 1 byte length1- 2 byte length
* Output:
* Return:
***********************************************************/
mtp_ret klvlist_2_data(klv_node_s *list, uint8_t **data, uint32_t *len, uint8_t type)
{
if (NULL == list || NULL == data || NULL == len) {
return MTP_INVALID_PARAM;
}
klv_node_s *node = list;
// count data len
uint32_t mk_data_len = 0;
while (node) {
mk_data_len += sizeof(klv_node_s) + node->len - sizeof(struct s_klv_node *);
node = node->next;
}
uint8_t *mk_data = (uint8_t *)tuya_ble_malloc(mk_data_len);
if (NULL == mk_data) {
return MTP_MALLOC_ERR;
}
// fill data
uint32_t offset = 0;
node = list;
while (node) {
mk_data[offset++] = node->id;
mk_data[offset++] = node->type;
if (1 == type) {
mk_data[offset++] = node->len >> 8;
mk_data[offset++] = node->len;
} else {
mk_data[offset++] = node->len;
}
if (node->len > 0) {
memcpy(&mk_data[offset], node->data, node->len);
}
offset += node->len;
node = node->next;
}
*len = offset;
*data = mk_data;
return MTP_OK;
}
/***********************************************************
* Function: data_2_klvlist
* description:
* Input: type: 0- 1 byte length1- 2 byte length
* Output:
* Return:
***********************************************************/
mtp_ret data_2_klvlist(uint8_t *data, uint32_t len, klv_node_s **list, uint8_t type)
{
uint16_t dp_len = 0;
//The data is parsed into a list of dp points dpid+dp_tp+len+data
if (NULL == data || NULL == list) {
return MTP_INVALID_PARAM;
}
uint32_t offset = 0;
klv_node_s *klv_list = NULL;
klv_node_s *node = NULL;
do {
// not full klv
if (type == 1) {
if ((len - offset) < 4) {
free_klv_list(klv_list);
return MTP_COM_ERROR;
}
} else {
if ((len - offset) < 3) {
free_klv_list(klv_list);
return MTP_COM_ERROR;
}
}
node = (klv_node_s *)tuya_ble_malloc(sizeof(klv_node_s));
if (NULL == node) {
free_klv_list(klv_list);
return MTP_MALLOC_ERR;
}
memset(node, 0, sizeof(klv_node_s));
if (1 == type) {
dp_len = (data[2 + offset] << 8) + data[3 + offset];
} else {
dp_len = data[2 + offset];
}
if (dp_len > 0) {
node->data = tuya_ble_malloc(dp_len);
if (node->data == NULL) {
tuya_ble_free(node->data);
tuya_ble_free((uint8_t *)node);
free_klv_list(klv_list);
return MTP_MALLOC_ERR;
}
}
node->id = data[offset++];
node->type = data[offset++];
if (1 == type) {
//offset++;
node->len = data[offset++];
node->len = (node->len << 8) + data[offset++];
} else {
node->len = data[offset++];
}
if ((len - offset) < node->len) {
// is remain data len enougn?
tuya_ble_free(node->data);
tuya_ble_free((uint8_t *)node);
free_klv_list(klv_list);
return MTP_COM_ERROR;
}
if (node->len > 0) {
memcpy(node->data, &data[offset], node->len);
}
offset += node->len;
node->next = klv_list;
klv_list = node;
} while (offset < len);
if (NULL == klv_list) {
return MTP_COM_ERROR;
}
*list = klv_list;
return MTP_OK;
}

View File

@ -1,100 +0,0 @@
/**
* \file tuya_ble_queue.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_queue.h"
#include "tuya_ble_type.h"
tuya_ble_status_t tuya_ble_queue_init(tuya_ble_queue_t *q, void *buf, uint8_t queue_size, uint8_t elem_size)
{
if (buf == NULL || q == NULL) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
q->buf = buf;
q->size = queue_size;
q->offset = elem_size;
q->rd_ptr = 0;
q->wr_ptr = 0;
q->used = 0;
return TUYA_BLE_SUCCESS;
}
tuya_ble_status_t tuya_ble_enqueue(tuya_ble_queue_t *q, void *in)
{
if (q->used >= q->size) {
return TUYA_BLE_ERR_NO_MEM;
}
memcpy((uint8_t *)q->buf + q->wr_ptr * q->offset, in, q->offset);
q->wr_ptr = (q->wr_ptr + 1) % q->size;
q->used++;
return TUYA_BLE_SUCCESS;
}
tuya_ble_status_t tuya_ble_queue_get(tuya_ble_queue_t *q, void *out)
{
if (q->used > 0) {
memcpy(out, (uint8_t *)q->buf + q->rd_ptr * q->offset, q->offset);
return TUYA_BLE_SUCCESS;
} else {
return TUYA_BLE_ERR_NOT_FOUND;
}
}
tuya_ble_status_t tuya_ble_dequeue(tuya_ble_queue_t *q, void *out)
{
if (q->used > 0) {
memcpy(out, (uint8_t *)q->buf + q->rd_ptr * q->offset, q->offset);
q->rd_ptr = (q->rd_ptr + 1) % q->size;
q->used--;
return TUYA_BLE_SUCCESS;
} else {
return TUYA_BLE_ERR_NOT_FOUND;
}
}
void tuya_ble_queue_decrease(tuya_ble_queue_t *q)
{
if (q->used > 0) {
q->rd_ptr = (q->rd_ptr + 1) % q->size;
q->used--;
}
}
void tuya_ble_queue_flush(tuya_ble_queue_t *q)
{
q->rd_ptr = 0;
q->wr_ptr = 0;
q->used = 0;
}
uint8_t tuya_ble_get_queue_used(tuya_ble_queue_t *q)
{
return q->used;
}

View File

@ -1,498 +0,0 @@
/**
* \file tuya_ble_storage.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_api.h"
#include "tuya_ble_port.h"
#include "tuya_ble_type.h"
#include "tuya_ble_main.h"
#include "tuya_ble_mem.h"
#include "tuya_ble_data_handler.h"
#include "tuya_ble_internal_config.h"
#include "tuya_ble_mutli_tsf_protocol.h"
#include "tuya_ble_storage.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_log.h"
typedef struct {
uint32_t crc;
uint32_t settings_version;
uint8_t h_id[H_ID_LEN];
uint8_t device_id[DEVICE_ID_LEN];
uint8_t mac[MAC_LEN];
uint8_t auth_key[AUTH_KEY_LEN];
} tuya_ble_auth_settings_old_t;
typedef struct {
uint32_t crc;
uint32_t settings_version;
tuya_ble_product_id_type_t pid_type;
uint8_t pid_len;
uint8_t common_pid[TUYA_BLE_PRODUCT_ID_MAX_LEN];
uint8_t login_key[LOGIN_KEY_LEN];
uint8_t ecc_secret_key[ECC_SECRET_KEY_LEN];
uint8_t device_virtual_id[DEVICE_VIRTUAL_ID_LEN];
uint8_t user_rand[PAIR_RANDOM_LEN];
uint8_t bound_flag;
} tuya_ble_sys_settings_old_t;
typedef struct {
tuya_ble_auth_settings_t flash_settings_auth;
tuya_ble_auth_settings_t flash_settings_auth_backup;
} tuya_ble_storage_auth_settings_t;
typedef struct {
tuya_ble_sys_settings_t flash_settings_sys;
tuya_ble_sys_settings_t flash_settings_sys_backup;
} tuya_ble_storage_sys_settings_t;
static bool buffer_value_is_all_x(uint8_t *buffer, uint16_t len, uint8_t value)
{
bool ret = true;
for (uint16_t i = 0; i < len; i++) {
if (buffer[i] != value) {
ret = false;
break;
}
}
return ret;
}
static uint32_t auth_settings_crc_get(tuya_ble_auth_settings_t const *p_settings)
{
// The crc is calculated from the s_dfu_settings struct, except the crc itself and the init command
return tuya_ble_crc32_compute((uint8_t *)(p_settings) + 4, sizeof(tuya_ble_auth_settings_t) - 4, NULL);
}
static bool auth_settings_crc_ok(tuya_ble_auth_settings_t const *p_settings, uint8_t *flash_update)
{
uint32_t crc, crc_old;
if (p_settings->crc != 0xFFFFFFFF) {
// CRC is set. Content must be valid
crc = auth_settings_crc_get(p_settings);
if (crc == p_settings->crc) {
return true;
} else {
crc_old = tuya_ble_crc32_compute((uint8_t *)(p_settings) + 4, sizeof(tuya_ble_auth_settings_old_t) - 4, NULL);
if (crc_old == p_settings->crc) {
*flash_update = 1;
return true;
}
}
}
return false;
}
static uint32_t sys_settings_crc_get(tuya_ble_sys_settings_t const *p_settings)
{
// The crc is calculated from the s_dfu_settings struct, except the crc itself and the init command
return tuya_ble_crc32_compute((uint8_t *)(p_settings) + 4, sizeof(tuya_ble_sys_settings_t) - 4, NULL);
}
static bool sys_settings_crc_ok(tuya_ble_sys_settings_t const *p_settings, uint8_t *flash_update)
{
uint32_t crc, crc_old;
if (p_settings->crc != 0xFFFFFFFF) {
// CRC is set. Content must be valid
crc = sys_settings_crc_get(p_settings);
if (crc == p_settings->crc) {
return true;
} else {
crc_old = tuya_ble_crc32_compute((uint8_t *)(p_settings) + 4, sizeof(tuya_ble_sys_settings_old_t) - 4, NULL);
if (crc_old == p_settings->crc) {
*flash_update = 1;
return true;
}
}
}
return false;
}
uint32_t tuya_ble_storage_load_settings(void)
{
uint32_t err_code = 0;
bool settings_valid ;
bool settings_backup_valid;
uint8_t auth_settings_flag = 1;
uint8_t sys_settings_flag = 1;
uint8_t auth_settings_update = 0;
uint8_t sys_settings_update = 0;
tuya_ble_storage_auth_settings_t *p_storage_settings_auth = NULL;
tuya_ble_storage_sys_settings_t *p_storage_settings_sys = NULL;
p_storage_settings_auth = (tuya_ble_storage_auth_settings_t *)tuya_ble_malloc(sizeof(tuya_ble_storage_auth_settings_t));
if (p_storage_settings_auth == NULL) {
TUYA_BLE_LOG_ERROR("p_storage_settings_auth malloc failed.");
memset(&tuya_ble_current_para.auth_settings, 0, sizeof(tuya_ble_auth_settings_t));
auth_settings_flag = 0;
} else {
memset(p_storage_settings_auth, 0, sizeof(tuya_ble_storage_auth_settings_t));
}
if (auth_settings_flag == 1) {
tuya_ble_nv_read(TUYA_BLE_AUTH_FLASH_ADDR, (uint8_t *)&p_storage_settings_auth->flash_settings_auth, sizeof(tuya_ble_auth_settings_t));
tuya_ble_nv_read(TUYA_BLE_AUTH_FLASH_BACKUP_ADDR, (uint8_t *)&p_storage_settings_auth->flash_settings_auth_backup, sizeof(tuya_ble_auth_settings_t));
settings_valid = auth_settings_crc_ok(&p_storage_settings_auth->flash_settings_auth, &auth_settings_update);
settings_backup_valid = auth_settings_crc_ok(&p_storage_settings_auth->flash_settings_auth_backup, &auth_settings_update);
if (settings_valid) {
memcpy(&tuya_ble_current_para.auth_settings, &p_storage_settings_auth->flash_settings_auth, sizeof(tuya_ble_auth_settings_t));
} else if (settings_backup_valid) {
memcpy(&tuya_ble_current_para.auth_settings, &p_storage_settings_auth->flash_settings_auth_backup, sizeof(tuya_ble_auth_settings_t));
} else {
memset(&tuya_ble_current_para.auth_settings, 0, sizeof(tuya_ble_auth_settings_t));
auth_settings_flag = 0;
}
if (auth_settings_update == 1) {
tuya_ble_storage_save_auth_settings();
auth_settings_update = 0;
}
tuya_ble_free((uint8_t *)p_storage_settings_auth);
}
p_storage_settings_sys = (tuya_ble_storage_sys_settings_t *)tuya_ble_malloc(sizeof(tuya_ble_storage_sys_settings_t));
if (p_storage_settings_sys == NULL) {
TUYA_BLE_LOG_ERROR("p_storage_settings_sys malloc failed.");
memset(&tuya_ble_current_para.sys_settings, 0, sizeof(tuya_ble_sys_settings_t));
sys_settings_flag = 0;
} else {
memset(p_storage_settings_sys, 0, sizeof(tuya_ble_storage_sys_settings_t));
}
if (sys_settings_flag == 1) {
tuya_ble_nv_read(TUYA_BLE_SYS_FLASH_ADDR, (uint8_t *)&p_storage_settings_sys->flash_settings_sys, sizeof(tuya_ble_sys_settings_t));
tuya_ble_nv_read(TUYA_BLE_SYS_FLASH_BACKUP_ADDR, (uint8_t *)&p_storage_settings_sys->flash_settings_sys_backup, sizeof(tuya_ble_sys_settings_t));
settings_valid = sys_settings_crc_ok(&p_storage_settings_sys->flash_settings_sys, &sys_settings_update);
settings_backup_valid = sys_settings_crc_ok(&p_storage_settings_sys->flash_settings_sys_backup, &sys_settings_update);
if (settings_valid) {
memcpy(&tuya_ble_current_para.sys_settings, &p_storage_settings_sys->flash_settings_sys, sizeof(tuya_ble_sys_settings_t));
} else if (settings_backup_valid) {
memcpy(&tuya_ble_current_para.sys_settings, &p_storage_settings_sys->flash_settings_sys_backup, sizeof(tuya_ble_sys_settings_t));
} else {
memset(&tuya_ble_current_para.sys_settings, 0, sizeof(tuya_ble_sys_settings_t));
tuya_ble_current_para.sys_settings.factory_test_flag = 0xFF;
sys_settings_flag = 0;
}
if (sys_settings_update == 1) {
tuya_ble_current_para.sys_settings.factory_test_flag = 0xFF;
tuya_ble_storage_save_sys_settings();
sys_settings_update = 0;
}
tuya_ble_free((uint8_t *)p_storage_settings_sys);
}
tuya_ble_current_para.pid_type = tuya_ble_current_para.sys_settings.pid_type;
tuya_ble_current_para.pid_len = tuya_ble_current_para.sys_settings.pid_len;
memcpy(tuya_ble_current_para.pid, tuya_ble_current_para.sys_settings.common_pid, tuya_ble_current_para.pid_len);
return err_code;
}
uint32_t tuya_ble_storage_save_auth_settings(void)
{
uint32_t err_code = 0;
tuya_ble_current_para.auth_settings.crc = tuya_ble_crc32_compute((uint8_t *)&tuya_ble_current_para.auth_settings + 4, sizeof(tuya_ble_current_para.auth_settings) - 4, NULL);
if (tuya_ble_nv_erase(TUYA_BLE_AUTH_FLASH_ADDR, TUYA_NV_ERASE_MIN_SIZE) == TUYA_BLE_SUCCESS) {
err_code = tuya_ble_nv_write(TUYA_BLE_AUTH_FLASH_ADDR, (uint8_t *)&tuya_ble_current_para.auth_settings, sizeof(tuya_ble_auth_settings_t));
if (err_code == TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_DEBUG("write flash_settings_auth data succeed!");
if (tuya_ble_nv_erase(TUYA_BLE_AUTH_FLASH_BACKUP_ADDR, TUYA_NV_ERASE_MIN_SIZE) == TUYA_BLE_SUCCESS) {
if (tuya_ble_nv_write(TUYA_BLE_AUTH_FLASH_BACKUP_ADDR, (uint8_t *)&tuya_ble_current_para.auth_settings, sizeof(tuya_ble_auth_settings_t)) != TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_ERROR("write flash_settings_auth data backup failed!");
err_code = 1;
}
} else {
TUYA_BLE_LOG_ERROR("erase flash_settings_auth data backup failed!");
err_code = 1;
}
} else {
TUYA_BLE_LOG_ERROR("write flash_settings_auth data failed!");
err_code = 1;
}
} else {
TUYA_BLE_LOG_ERROR("erase flash_settings_auth data failed!");
err_code = 1;
}
return err_code;
}
uint32_t tuya_ble_storage_save_sys_settings(void)
{
uint32_t err_code = 0;
#if (TUYA_BLE_DEVICE_AUTH_DATA_STORE)
tuya_ble_current_para.sys_settings.crc = tuya_ble_crc32_compute((uint8_t *)&tuya_ble_current_para.sys_settings + 4, sizeof(tuya_ble_sys_settings_t) - 4, NULL);
if (tuya_ble_nv_erase(TUYA_BLE_SYS_FLASH_ADDR, TUYA_NV_ERASE_MIN_SIZE) == TUYA_BLE_SUCCESS) {
err_code = tuya_ble_nv_write(TUYA_BLE_SYS_FLASH_ADDR, (uint8_t *)&tuya_ble_current_para.sys_settings, sizeof(tuya_ble_sys_settings_t));
if (err_code == TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_INFO("write flash_settings_sys data succeed!");
if (tuya_ble_nv_erase(TUYA_BLE_SYS_FLASH_BACKUP_ADDR, TUYA_NV_ERASE_MIN_SIZE) == TUYA_BLE_SUCCESS) {
if (tuya_ble_nv_write(TUYA_BLE_SYS_FLASH_BACKUP_ADDR, (uint8_t *)&tuya_ble_current_para.sys_settings, sizeof(tuya_ble_sys_settings_t)) != TUYA_BLE_SUCCESS) {
TUYA_BLE_LOG_ERROR("write flash_settings_sys data backup failed!");
err_code = 1;
}
} else {
TUYA_BLE_LOG_ERROR("erase flash_settings_sys data backup failed!");
err_code = 1;
}
} else {
TUYA_BLE_LOG_ERROR("write flash_settings_sys data failed!");
err_code = 1;
}
} else {
TUYA_BLE_LOG_ERROR("erase flash_settings_sys data failed!");
err_code = 1;
}
#endif
return err_code;
}
uint32_t tuya_ble_storage_init(void)
{
uint32_t err = 0;
tuya_ble_nv_init();
#if (TUYA_BLE_DEVICE_AUTH_DATA_STORE)
tuya_ble_storage_load_settings();
#endif
return err;
}
#if (TUYA_BLE_DEVICE_AUTH_DATA_STORE)
/**
* @brief Function for write pid to nv
*
* @note
*
* */
tuya_ble_status_t tuya_ble_storage_write_pid(tuya_ble_product_id_type_t pid_type, uint8_t pid_len, uint8_t *pid)
{
tuya_ble_status_t ret = TUYA_BLE_SUCCESS;
uint8_t is_write = 0;
if (pid_len > TUYA_BLE_PRODUCT_ID_MAX_LEN) {
return TUYA_BLE_ERR_INVALID_PARAM;
}
if ((pid_type != tuya_ble_current_para.pid_type) || (pid_len != tuya_ble_current_para.pid_len)) {
tuya_ble_current_para.pid_type = pid_type;
tuya_ble_current_para.pid_len = pid_len;
memcpy(tuya_ble_current_para.pid, pid, pid_len);
tuya_ble_current_para.sys_settings.pid_type = pid_type;
tuya_ble_current_para.sys_settings.pid_len = pid_len;
memcpy(tuya_ble_current_para.sys_settings.common_pid, pid, pid_len);
is_write = 1;
} else if (memcmp(pid, tuya_ble_current_para.pid, pid_len) != 0) {
tuya_ble_current_para.pid_type = pid_type;
tuya_ble_current_para.pid_len = pid_len;
memcpy(tuya_ble_current_para.pid, pid, pid_len);
tuya_ble_current_para.sys_settings.pid_type = pid_type;
tuya_ble_current_para.sys_settings.pid_len = pid_len;
memcpy(tuya_ble_current_para.sys_settings.common_pid, pid, pid_len);
is_write = 1;
} else {
}
if (is_write == 1) {
if (tuya_ble_storage_save_sys_settings()) {
ret = TUYA_BLE_ERR_BUSY;
}
}
return ret;
}
/**
* @brief Function for write hid to nv
*
* @note
*
* */
tuya_ble_status_t tuya_ble_storage_write_hid(uint8_t *hid, uint8_t len)
{
tuya_ble_status_t ret = TUYA_BLE_SUCCESS;
if (len != H_ID_LEN) {
ret = TUYA_BLE_ERR_INVALID_PARAM;
} else {
if (memcmp(hid, tuya_ble_current_para.auth_settings.h_id, H_ID_LEN) != 0) {
memcpy(tuya_ble_current_para.auth_settings.h_id, hid, H_ID_LEN);
if (tuya_ble_storage_save_auth_settings()) {
ret = TUYA_BLE_ERR_BUSY;
}
}
}
return ret;
}
/**
* @brief Function for read id parameters
*
* @note
*
* */
tuya_ble_status_t tuya_ble_storage_read_id_info(tuya_ble_factory_id_data_t *id)
{
tuya_ble_status_t ret = TUYA_BLE_SUCCESS;
id->pid_type = tuya_ble_current_para.pid_type;
id->pid_len = tuya_ble_current_para.pid_len;
memcpy(id->pid, tuya_ble_current_para.pid, tuya_ble_current_para.pid_len);
memcpy(id->h_id, tuya_ble_current_para.auth_settings.h_id, H_ID_LEN);
memcpy(id->device_id, tuya_ble_current_para.auth_settings.device_id, DEVICE_ID_LEN);
memcpy(id->mac, tuya_ble_current_para.auth_settings.mac, MAC_LEN);
memcpy(id->auth_key, tuya_ble_current_para.auth_settings.auth_key, AUTH_KEY_LEN);
return ret;
}
/**
* @brief Function for write auth key/uuid/mac/pid
*
* @note If the id length is 0, the corresponding id will not be written.
*
* */
tuya_ble_status_t tuya_ble_storage_write_auth_key_device_id_mac(uint8_t *auth_key, uint8_t auth_key_len, uint8_t *device_id, uint8_t device_id_len,
uint8_t *mac, uint8_t mac_len, uint8_t *mac_string, uint8_t mac_string_len, uint8_t *pid, uint8_t pid_len)
{
tuya_ble_status_t ret = TUYA_BLE_SUCCESS;
uint8_t is_write = 0;
if (((auth_key_len != AUTH_KEY_LEN) && (auth_key_len != 0)) || ((device_id_len != DEVICE_ID_LEN) && (device_id_len != 0)) || ((mac_len != MAC_LEN) && (mac_len != 0))) {
ret = TUYA_BLE_ERR_INVALID_PARAM;
} else {
if (auth_key_len == AUTH_KEY_LEN) {
if (memcmp(tuya_ble_current_para.auth_settings.auth_key, auth_key, AUTH_KEY_LEN) != 0) {
memcpy(tuya_ble_current_para.auth_settings.auth_key, auth_key, AUTH_KEY_LEN);
is_write = 1;
}
}
if (device_id_len == DEVICE_ID_LEN) {
if (memcmp(tuya_ble_current_para.auth_settings.device_id, device_id, DEVICE_ID_LEN) != 0) {
memcpy(tuya_ble_current_para.auth_settings.device_id, device_id, DEVICE_ID_LEN);
is_write = 1;
}
}
if (mac_len == MAC_LEN) {
if (memcmp(tuya_ble_current_para.auth_settings.mac, mac, MAC_LEN) != 0) {
memcpy(tuya_ble_current_para.auth_settings.mac, mac, MAC_LEN);
memcpy(tuya_ble_current_para.auth_settings.mac_string, mac_string, MAC_LEN * 2);
is_write = 1;
}
}
if (pid_len > 0) {
if ((tuya_ble_current_para.auth_settings.pid_len != pid_len) || (memcmp(tuya_ble_current_para.auth_settings.factory_pid, pid, pid_len) != 0)) {
memcpy(tuya_ble_current_para.auth_settings.factory_pid, pid, pid_len);
tuya_ble_current_para.auth_settings.pid_len = pid_len;
tuya_ble_current_para.auth_settings.pid_type = (uint8_t)TUYA_BLE_PRODUCT_ID_TYPE_PID;
is_write = 1;
}
}
if (is_write == 1) {
#if (!TUYA_BLE_DEVICE_AUTH_DATA_STORE_EXT_MEDIUM)
if (tuya_ble_storage_save_auth_settings()) {
ret = TUYA_BLE_ERR_BUSY;
}
#else
tuya_ble_current_para.auth_settings.crc = tuya_ble_crc32_compute((uint8_t *)&tuya_ble_current_para.auth_settings + 4, sizeof(tuya_ble_current_para.auth_settings) - 4, NULL);
if (tuya_ble_storage_private_data(PRIVATE_DATA_TUYA_AUTH_TOKEN, (uint8_t *)&tuya_ble_current_para.auth_settings, sizeof(tuya_ble_auth_settings_t))) {
ret = TUYA_BLE_ERR_BUSY;
}
#endif // (!TUYA_BLE_DEVICE_AUTH_DATA_STORE_EXT_MEDIUM)
else {
/* force clear device_virtual_id info */
//if(tuya_ble_current_para.sys_settings.bound_flag==1)
{
memset(tuya_ble_current_para.sys_settings.device_virtual_id, 0, DEVICE_VIRTUAL_ID_LEN);
memset(tuya_ble_current_para.sys_settings.login_key, 0, LOGIN_KEY_LEN);
tuya_ble_current_para.sys_settings.bound_flag = 0;
tuya_ble_storage_save_sys_settings();
tuya_ble_adv_change();
tuya_ble_connect_status_set(UNBONDING_UNCONN);
TUYA_BLE_LOG_INFO("The state has changed, current bound flag = %d", tuya_ble_current_para.sys_settings.bound_flag);
}
}
}
}
return ret;
}
#endif

View File

@ -1,284 +0,0 @@
/**
* \file tuya_ble_unix_time.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_unix_time.h"
#define UTC_BASE_YEAR 1970
#define MONTH_PER_YEAR 12
#define DAY_PER_YEAR 365
#define SEC_PER_DAY 86400
#define SEC_PER_HOUR 3600
#define SEC_PER_MIN 60
/* Number of days per month */
static const uint8_t g_day_per_mon[MONTH_PER_YEAR] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
/**
* @brief Function for Determine whether it is a leap year.
*
* @return 1leap year
* @note
*.
* */
static uint8_t applib_dt_is_leap_year(uint16_t year)
{
/*----------------------------------------------------------------*/
/* Local Variables */
/*----------------------------------------------------------------*/
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
if ((year % 400) == 0) {
return 1;
} else if ((year % 100) == 0) {
return 0;
} else if ((year % 4) == 0) {
return 1;
} else {
return 0;
}
}
/**
* @brief Function for obtain the days of month.
*
* @return days
* @note
*.
* */
static uint8_t applib_dt_last_day_of_mon(uint8_t month, uint16_t year)
{
/*----------------------------------------------------------------*/
/* Local Variables */
/*----------------------------------------------------------------*/
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
if ((month == 0) || (month > 12)) {
return g_day_per_mon[1] + applib_dt_is_leap_year(year);
}
if (month != 2) {
return g_day_per_mon[month - 1];
} else {
return g_day_per_mon[1] + applib_dt_is_leap_year(year);
}
}
/**
* @brief Function for get the corresponding week based on the given date.
*
* @return
* @note 0-Sunday 6-Saturday
*.
* */
static uint8_t applib_dt_dayindex(uint16_t year, uint8_t month, uint8_t day)
{
int8_t century_code, year_code, month_code, day_code;
int32_t week = 0;
century_code = year_code = month_code = day_code = 0;
if (month == 1 || month == 2) {
century_code = (year - 1) / 100;
year_code = (year - 1) % 100;
month_code = month + 12;
day_code = day;
} else {
century_code = year / 100;
year_code = year % 100;
month_code = month;
day_code = day;
}
week = year_code + year_code / 4 + century_code / 4 - 2 * century_code + 26 * (month_code + 1) / 10 + day_code - 1;
week = week > 0 ? (week % 7) : ((week % 7) + 7);
return week;
}
/**
* @brief Function for Get the corresponding date according to the UTC timestamp.
*
* @param[in] daylightSaving:daylight saving time
* @return
* @note
*.
* */
void tuya_ble_utc_sec_2_mytime(uint32_t utc_sec, tuya_ble_time_struct_data_t *result, bool daylightSaving)
{
/*----------------------------------------------------------------*/
/* Local Variables */
/*----------------------------------------------------------------*/
int32_t sec, day;
uint16_t y;
uint8_t m;
uint16_t d;
// uint8_t dst;
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
if (daylightSaving) {
utc_sec += SEC_PER_HOUR;
}
/* hour, min, sec */
/* hour */
sec = utc_sec % SEC_PER_DAY;
result->nHour = sec / SEC_PER_HOUR;
/* min */
sec %= SEC_PER_HOUR;
result->nMin = sec / SEC_PER_MIN;
/* sec */
result->nSec = sec % SEC_PER_MIN;
/* year, month, day */
/* year */
/* year */
day = utc_sec / SEC_PER_DAY;
for (y = UTC_BASE_YEAR; day > 0; y++) {
d = (DAY_PER_YEAR + applib_dt_is_leap_year(y));
if (day >= d) {
day -= d;
} else {
break;
}
}
result->nYear = y;
for (m = 1; m < MONTH_PER_YEAR; m++) {
d = applib_dt_last_day_of_mon(m, y);
if (day >= d) {
day -= d;
} else {
break;
}
}
result->nMonth = m;
result->nDay = (uint8_t)(day + 1);
result->DayIndex = applib_dt_dayindex(result->nYear, result->nMonth, result->nDay);
}
/**
* @brief Function for Get the UTC timestamp according to corresponding date .
*
* @param[in] daylightSaving:daylight saving time
* @return
* @note
*.
* */
uint32_t tuya_ble_mytime_2_utc_sec(tuya_ble_time_struct_data_t *currTime, bool daylightSaving)
{
/*----------------------------------------------------------------*/
/* Local Variables */
/*----------------------------------------------------------------*/
uint16_t i;
uint32_t no_of_days = 0;
uint32_t utc_time;
uint8_t dst = 1;
/*----------------------------------------------------------------*/
/* Code Body */
/*----------------------------------------------------------------*/
if (currTime->nYear < UTC_BASE_YEAR) {
return 0;
}
/* year */
for (i = UTC_BASE_YEAR; i < currTime->nYear; i++) {
no_of_days += (DAY_PER_YEAR + applib_dt_is_leap_year(i));
}
/* month */
for (i = 1; i < currTime->nMonth; i++) {
no_of_days += applib_dt_last_day_of_mon((unsigned char) i, currTime->nYear);
}
/* day */
no_of_days += (currTime->nDay - 1);
/* sec */
utc_time = (unsigned int) no_of_days * SEC_PER_DAY + (unsigned int)(currTime->nHour * SEC_PER_HOUR +
currTime->nMin * SEC_PER_MIN + currTime->nSec);
if (dst && daylightSaving) {
utc_time -= SEC_PER_HOUR;
}
return utc_time;
}
void tuya_ble_utc_sec_2_mytime_string(uint32_t utc_sec, bool daylightSaving, char *s)
{
tuya_ble_time_struct_data_t rtc_time = {0};
uint32_t temp = 0;
tuya_ble_utc_sec_2_mytime(utc_sec, &rtc_time, daylightSaving);
temp = rtc_time.nYear;
s[0] = temp / 1000 + 0x30;
temp = rtc_time.nYear % 1000;
s[1] = temp / 100 + 0x30;
temp = temp % 100;
s[2] = temp / 10 + 0x30;
s[3] = temp % 10 + 0x30;
s[4] = '-';
s[5] = rtc_time.nMonth / 10 + 0x30;
s[6] = rtc_time.nMonth % 10 + 0x30;
s[7] = '-';
s[8] = rtc_time.nDay / 10 + 0x30;
s[9] = rtc_time.nDay % 10 + 0x30;
s[10] = ' ';
s[11] = rtc_time.nHour / 10 + 0x30;
s[12] = rtc_time.nHour % 10 + 0x30;
s[13] = ':';
s[14] = rtc_time.nMin / 10 + 0x30;
s[15] = rtc_time.nMin % 10 + 0x30;
s[16] = ':';
s[17] = rtc_time.nSec / 10 + 0x30;
s[18] = rtc_time.nSec % 10 + 0x30;
s[19] = '\0';
}

View File

@ -1,773 +0,0 @@
/**
* \file tuya_ble_utils.c
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#include "tuya_ble_stdlib.h"
#include "tuya_ble_utils.h"
#include "tuya_ble_port.h"
#include "tuya_ble_mem.h"
int32_t tuya_ble_count_bits(uint32_t data)
{
int32_t i = 0;
int32_t cnt = 0;
for (i = 0; i < 32; i++) {
if (data & 0x01) {
cnt++;
}
data >>= 1;
}
return cnt;
}
int32_t tuya_ble_rand_number(int32_t min, int32_t max)
{
static bool is_srand_init = false;
int32_t num;
if (!is_srand_init) {
is_srand_init = true;
//srand(time(NULL));
}
num = rand() % (max - min) + min; // [min<=num<=max]
return num;
}
void tuya_ble_inverted_array(uint8_t *array, uint16_t length)
{
uint8_t temp;
uint16_t i, j;
for (i = 0, j = length - 1; i < j; i++, j--) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
bool tuya_ble_buffer_value_is_all_x(uint8_t *buffer, uint16_t len, uint8_t value)
{
bool ret = true;
for (uint16_t i = 0; i < len; i++) {
if (buffer[i] != value) {
ret = false;
break;
}
}
return ret;
}
uint8_t tuya_ble_check_sum(uint8_t *pbuf, uint16_t len)
{
uint32_t i = 0, ck_sum = 0;
for (i = 0; i < len ; i++) {
ck_sum += pbuf[i];
}
return (uint8_t)ck_sum;
}
uint8_t tuya_ble_check_num(uint8_t *buf, uint8_t num)
{
uint8_t i = 0;
for (; i < buf[0]; i++) {
if (buf[i + 1] == num) {
return 1;
}
}
return 0;
}
void tuya_ble_hextoascii(uint8_t *hexbuf, uint8_t len, uint8_t *ascbuf)
{
uint8_t i = 0, j = 0, temp = 0;
for (i = 0; i < len; i++) {
temp = (hexbuf[i] >> 4) & 0xf;
if (temp <= 9) {
ascbuf[j] = temp + 0x30;
} else {
ascbuf[j] = temp + 87;
}
j++;
temp = (hexbuf[i]) & 0xf;
if (temp <= 9) {
ascbuf[j] = temp + 0x30;
} else {
ascbuf[j] = temp + 87;
}
j++;
}
}
void tuya_ble_hextostr(uint8_t *hexbuf, uint8_t len, uint8_t *strbuf)
{
uint8_t i = 0, j = 0, temp = 0;
for (i = 0; i < len; i++) {
temp = (hexbuf[i] >> 4) & 0x0f;
if (temp <= 9) {
strbuf[j] = temp + 0x30;
} else {
strbuf[j] = temp + 87;
}
j++;
temp = (hexbuf[i]) & 0x0f;
if (temp <= 9) {
strbuf[j] = temp + 0x30;
} else {
strbuf[j] = temp + 87;
}
j++;
}
strbuf[j] = 0x00;
}
void tuya_ble_asciitohex(uint8_t *ascbuf, uint8_t *hexbuf)
{
uint8_t i = 0, j = 0;
while (ascbuf[i]) {
j++;
if ((ascbuf[i] >= 0x30) && (ascbuf[i] <= 0x39)) {
hexbuf[j] = ((ascbuf[i] - 0x30) << 4);
} else if ((ascbuf[i] >= 65) && (ascbuf[i] <= 70)) {
hexbuf[j] = ((ascbuf[i] - 55) << 4);
} else if ((ascbuf[i] >= 97) && (ascbuf[i] <= 102)) {
hexbuf[j] = ((ascbuf[i] - 87) << 4);
}
i++;
if ((ascbuf[i] >= 0x30) && (ascbuf[i] <= 0x39)) {
hexbuf[j] |= (ascbuf[i] - 0x30);
} else if ((ascbuf[i] >= 65) && (ascbuf[i] <= 70)) {
hexbuf[j] |= (ascbuf[i] - 55);
} else if ((ascbuf[i] >= 97) && (ascbuf[i] <= 102)) {
hexbuf[j] |= (ascbuf[i] - 87);
}
i++;
}
hexbuf[0] = j;
}
uint8_t tuya_ble_char_2_ascii(uint8_t data)
{
uint8_t ret = 0xff;
if ((data >= 48) && (data <= 57)) {
ret = data - 48;
} else if ((data >= 65) && (data <= 70)) {
ret = data - 55;
} else if ((data >= 97) && (data <= 102)) {
ret = data - 87;
}
return ret;
}
void tuya_ble_str_to_hex(uint8_t *str_buf, uint8_t str_len, uint8_t *hex_buf)
{
uint8_t data_tmp = 0, i = 0, j = 0;
for (j = 0 ; j < str_len ; j++) {
data_tmp = tuya_ble_char_2_ascii(str_buf[j]);
if (data_tmp != 0xff) {
hex_buf[i] = (data_tmp << 4);
} else {
return;
}
j++;
data_tmp = tuya_ble_char_2_ascii(str_buf[j]);
if (data_tmp != 0xff) {
hex_buf[i] += data_tmp;
} else {
return;
}
i++;
}
}
void tuya_ble_swap(int16_t *a, int16_t *b)
{
int16_t temp;
temp = *a;
*a = *b;
*b = temp;
}
int32_t tuya_ble_hex2int(uint8_t mhex)
{
switch (mhex) {
case '0':
return 0;
case '1':
return 1;
case '2':
return 2;
case '3':
return 3;
case '4':
return 4;
case '5':
return 5;
case '6':
return 6;
case '7':
return 7;
case '8':
return 8;
case '9':
return 9;
case 'a':
case 'A':
return 10;
case 'b':
case 'B':
return 11;
case 'c':
case 'C':
return 12;
case 'd':
case 'D':
return 13;
case 'e':
case 'E':
return 14;
case 'f':
case 'F':
return 15;
default:
return -1;
}
}
char tuya_ble_hexstr2int(uint8_t *hexstr, int32_t len, uint8_t *sum)
{
*sum = 0;
int32_t value;
for (int32_t i = 0; i < len; i++) {
value = tuya_ble_hex2int(hexstr[i]);
if (value == -1) {
return 0;
}
(*sum) = (*sum) << 4;
(*sum) += value;
}
return 1;
}
char tuya_ble_hexstr2hex(uint8_t *hexstr, int32_t len, uint8_t *hex)
{
for (uint8_t i = 0; i < len; i += 2) {
if (tuya_ble_hexstr2int(&hexstr[i], 2, &hex[i / 2]) == 0) {
return 0;
}
}
return 1;
}
static void swapX(const uint8_t *src, uint8_t *dst, int32_t len)
{
int32_t i;
for (i = 0; i < len; i++) {
dst[len - 1 - i] = src[i];
}
}
void tuya_ble_swap24(uint8_t dst[3], const uint8_t src[3])
{
swapX(src, dst, 3);
}
void tuya_ble_swap32(uint8_t dst[4], const uint8_t src[4])
{
swapX(src, dst, 4);
}
void tuya_ble_swap48(uint8_t dst[7], const uint8_t src[7])
{
swapX(src, dst, 6);
}
void tuya_ble_swap56(uint8_t dst[7], const uint8_t src[7])
{
swapX(src, dst, 7);
}
void tuya_ble_swap64(uint8_t dst[8], const uint8_t src[8])
{
swapX(src, dst, 8);
}
void tuya_ble_swap128(uint8_t dst[16], const uint8_t src[16])
{
swapX(src, dst, 16);
}
uint16_t tuya_ble_crc16_compute(uint8_t *p_data, uint16_t size, uint16_t *p_crc)
{
uint16_t poly[2] = {0, 0xa001}; //0x8005 <==> 0xa001
uint16_t crc;
int i, j;
crc = (p_crc == NULL) ? 0xFFFF : *p_crc;
for (j = size; j > 0; j--) {
unsigned char ds = *p_data++;
for (i = 0; i < 8; i++) {
crc = (crc >> 1) ^ poly[(crc ^ ds) & 1];
ds = ds >> 1;
}
}
return crc;
}
uint32_t tuya_ble_crc32_compute(uint8_t const *p_data, uint32_t size, uint32_t const *p_crc)
{
uint32_t crc;
crc = (p_crc == NULL) ? 0xFFFFFFFF : ~(*p_crc);
for (uint32_t i = 0; i < size; i++) {
crc = crc ^ p_data[i];
for (uint32_t j = 8; j > 0; j--) {
crc = (crc >> 1) ^ (0xEDB88320U & ((crc & 1) ? 0xFFFFFFFF : 0));
}
}
return ~crc;
}
/**@brief Function for checking if a pointer value is aligned to a 4 byte boundary.
*
* @param[in] p Pointer value to be checked.
*
* @return TRUE if pointer is aligned to a 4 byte boundary, FALSE otherwise.
*/
bool tuya_ble_is_word_aligned_tuya(void const *p)
{
return (((uintptr_t)p & 0x03) == 0);
}
void tuya_ble_device_id_20_to_16(uint8_t *in, uint8_t *out)
{
uint8_t i, j;
uint8_t temp[4];
for (i = 0; i < 5; i++) {
for (j = i * 4; j < (i * 4 + 4); j++) {
if ((in[j] >= 0x30) && (in[j] <= 0x39)) {
temp[j - i * 4] = in[j] - 0x30;
} else if ((in[j] >= 0x41) && (in[j] <= 0x5A)) {
temp[j - i * 4] = in[j] - 0x41 + 36;
} else if ((in[j] >= 0x61) && (in[j] <= 0x7A)) {
temp[j - i * 4] = in[j] - 0x61 + 10;
} else {
}
}
out[i * 3] = temp[0] & 0x3F;
out[i * 3] <<= 2;
out[i * 3] |= ((temp[1] >> 4) & 0x03);
out[i * 3 + 1] = temp[1] & 0x0F;
out[i * 3 + 1] <<= 4;
out[i * 3 + 1] |= ((temp[2] >> 2) & 0x0F);
out[i * 3 + 2] = temp[2] & 0x03;
out[i * 3 + 2] <<= 6;
out[i * 3 + 2] |= temp[3] & 0x3F;
}
out[15] = 0xFF;
}
void tuya_ble_device_id_16_to_20(uint8_t *in, uint8_t *out)
{
uint8_t i, j;
uint8_t temp[4];
for (i = 0; i < 5; i++) {
j = i * 3;
temp[j - i * 3] = (in[j] >> 2) & 0x3F;
temp[j - i * 3 + 1] = in[j] & 0x03;
temp[j - i * 3 + 1] <<= 4;
temp[j - i * 3 + 1] |= (in[j + 1] >> 4) & 0x0F;
temp[j - i * 3 + 2] = (in[j + 1] & 0x0F) << 2;
temp[j - i * 3 + 2] |= ((in[j + 2] & 0xC0) >> 6) & 0x03;
temp[j - i * 3 + 3] = in[j + 2] & 0x3F;
for (j = i * 4; j < (i * 4 + 4); j++) {
if ((temp[j - i * 4] >= 0) && (temp[j - i * 4] <= 9)) {
out[j] = temp[j - i * 4] + 0x30;
} else if ((temp[j - i * 4] >= 10) && (temp[j - i * 4] <= 35)) {
out[j] = temp[j - i * 4] + 87;
} else if ((temp[j - i * 4] >= 36) && (temp[j - i * 4] <= 61)) {
out[j] = temp[j - i * 4] + 29;
} else {
}
}
}
}
/**
* @brief Function for search character/symbol index from input string
*
* @param
* [in]data : pointer to input data
* [in]data : Number of bytes of data
* [in]symbol : Search symbol or character, Such as ':' or ','
* [out]index[] : Array of indexs
*
* @return The number of matched character/symbol
*
* @note
*
* */
int32_t tuya_ble_search_symbol_index(char *data, uint16_t len, char symbol, uint8_t index[])
{
int32_t i;
uint8_t index_buf[64] = {0};
uint8_t symbol_cnt = 0;
if (data == NULL || len == 0 || index == NULL) {
return symbol_cnt;
}
for (i = 0; i < len; i++) {
if (data[i] == symbol) {
index_buf[symbol_cnt] = i;
symbol_cnt += 1;
if (symbol_cnt >= sizeof(index_buf)) {
/* error, too many symbols */
break;
}
}
}
if (symbol_cnt != 0) {
memcpy(index, index_buf, symbol_cnt);
}
return symbol_cnt;
}
int32_t tuya_ble_ascii_to_int(char *ascii, uint16_t len)
{
int32_t i;
int32_t num = 0;
bool negative = false;
if (ascii == NULL || len == 0) {
return num;
}
if (ascii[0] == 0x2D) {
negative = true;
} else {
num *= 10;
num += ascii[0] - '0';
}
for (i = 1; i < len; i++) {
num *= 10;
num += ascii[i] - '0';
}
if (negative) {
num = -1 * num;
}
return num;
}
static uint8_t base64_decode(const uint8_t *input, uint16_t inlen, uint8_t *output, uint16_t *outlen)
{
const char *base64_tbl = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
uint8_t reverse_tbl[256] = {0};
int32_t off = 0;
int32_t i = 0;
if (NULL == input) {
return 1;
}
if (inlen == 0) {
inlen = strlen((char *)input);
}
if (inlen == 0 || (inlen % 4 != 0)) {
return 1;
}
for (i = 0; i < 64; i++) {
reverse_tbl[base64_tbl[i]] = i;
}
for (i = 0; i < inlen - 4; i += 4) {
output[off++] = (reverse_tbl[input[i]] << 2) | ((reverse_tbl[input[i + 1]] >> 4) & 0xFF);
output[off++] = (reverse_tbl[input[i + 1]] << 4) | ((reverse_tbl[input[i + 2]] >> 2) & 0xFF);
output[off++] = (reverse_tbl[input[i + 2]] << 6) | ((reverse_tbl[input[i + 3]]) & 0xFF);
}
if (input[i + 2] == '=') {
output[off++] = (reverse_tbl[input[i]] << 2) | ((reverse_tbl[input[i + 1]] >> 4) & 0xFF);
} else if (input[i + 3] == '=') {
output[off++] = (reverse_tbl[input[i]] << 2) | ((reverse_tbl[input[i + 1]] >> 4) & 0xFF);
output[off++] = (reverse_tbl[input[i + 1]] << 4) | ((reverse_tbl[input[i + 2]] >> 2) & 0xFF);
} else {
output[off++] = (reverse_tbl[input[i]] << 2) | ((reverse_tbl[input[i + 1]] >> 4) & 0xFF);
output[off++] = (reverse_tbl[input[i + 1]] << 4) | ((reverse_tbl[input[i + 2]] >> 2) & 0xFF);
output[off++] = (reverse_tbl[input[i + 2]] << 6) | ((reverse_tbl[input[i + 3]]) & 0xFF);
}
if (NULL != outlen) {
*outlen = off;
}
return 0;
}
static int32_t delChar(char *s, uint16_t len, char match_char)
{
int32_t i, j;
int32_t counter = 0;
for (i = 0; i < len; i++) {
if (s[i] == match_char) {
counter++;
for (j = i; j < len; j++) {
s[j] = s[j + 1];
i--;
}
}
}
return counter;
}
/**
* @brief Function for pem format ecc key to hex foramt
*
* @param
* [in]pem : pointer to pem data
* [out]key : pointer to output data, hex format ecc key
* [out]key_len: Number of bytes of key.
*
* @return 0 - failed, 1 - success
*
* @note developer could use tuya_ble_ecc_key_pem2hex_example() function to test
*
* */
int32_t tuya_ble_ecc_key_pem2hex(const char *pem, uint8_t *key, uint16_t *key_len)
{
char buf1[256] = {0};
char buf2[256] = {0};
uint16_t inlen = 0;
uint16_t i, j, k = 0;
uint16_t len, len1, len2 = 0;
if (NULL == pem) {
return 0;
}
inlen = strlen(pem);
if (inlen > 256) {
return 0;
}
//head
if ((pem[0] != '-') || (pem[1] != '-') || (pem[2] != '-') || (pem[3] != '-') || (pem[4] != '-')) {
return 0;
}
//tail
if ((pem[inlen - 1] != '-') || (pem[inlen - 2] != '-') || (pem[inlen - 3] != '-') || (pem[inlen - 4] != '-') || (pem[inlen - 5] != '-')) {
return 0;
}
//find head end
for (i = 5; i < inlen - 5; i++) {
if (pem[i] == '-') {
if ((pem[i + 1] != '-') || (pem[i + 2] != '-') || (pem[i + 3] != '-') || (pem[i + 4] != '-')) {
return 0;
}
len1 = i + 5;
break;
}
}
//remove head
memcpy(buf1, pem + len1, inlen - len1);
//find tail
for (i = 0; i < inlen - len1; i++) {
if (buf1[i] == '-') {
if ((buf1[i + 1] != '-') || (buf1[i + 2] != '-') || (buf1[i + 3] != '-') || (buf1[i + 4] != '-')) {
return 0;
}
len2 = i;
break;
}
}
len = len2;
//remove \n
len1 = delChar(buf1, len, '\n');
len = len - len1;
//remove \r
len1 = delChar(buf1, len, '\r');
len = len - len1;
//decode
base64_decode((uint8_t *)buf1, len, (uint8_t *)buf2, (uint16_t *)&len2);
//next is asn.1 decode
if (buf2[0] != 0x30) { //0x30
return 0;
}
len1 = buf2[1];//0x30 0x41
if ((len1 + 2) != len2) {
return 0;
}
if (buf2[2] != 0x02) { //0x30 0x41 0x20 0x01 0x00
return 0;
}
if (buf2[5] != 0x30) {
return 0;
}
len1 = buf2[6];
if (buf2[7 + len1] != 0x04) { //0x04
return 0;
}
// len2 = buf2[8+len1];//0x04 0x27
if (buf2[9 + len1] != 0x30) { //0x30
return 0;
}
// len = buf2[10+len1];//0x25
if (buf2[11 + len1] != 0x02) { //0x02
return 0;
}
if (buf2[14 + len1] != 0x04) { //0x04
return 0;
}
*key_len = buf2[15 + len1];
memcpy(key, &buf2[16 + len1], *key_len);
return 1;
}
void tuya_ble_ecc_key_pem2hex_example(void)
{
uint8_t key[64] = {0};
uint16_t keylen = 0;
char test_char[] =
"-----BEGIN PRIVATE KEY-----MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCBX5s0E0DJowr3ibkG41jfvjRFgaoCO7v8fU/Wq/xLlDQ==-----END PRIVATE KEY-----";
tuya_ble_ecc_key_pem2hex(test_char, key, &keylen);
/* output hex format key */
// 57 E6 CD 04 D0 32 68 C2 BD E2 6E 41 B8 D6 37 EF
// 8D 11 60 6A 80 8E EE FF 1F 53 F5 AA FF 12 E5 0D
}
/**
* @brief Function for extract r+s from der from ecdsa sign
*
* @param
* [in]der : pointer to der data
* [out]raw_rs : pointer to output data, the raw data[r+s] of der
*
* @return 0 - failed, 1 - success
*
* @note
*
* */
int32_t tuya_ble_ecc_sign_secp256r1_extract_raw_from_der(const char *der, uint8_t *raw_rs)
{
/* extract r + s from der */
int pos = 0;
uint8_t raw[64] = {0};
if (der == NULL || raw_rs == NULL) {
return 0;
}
if (der[3] != 0x20) {
memcpy(raw, &der[5], 32);
pos = 5 + 32;
} else {
memcpy(raw, &der[4], 32);
pos = 4 + 32;
}
// 37
if (der[pos + 1] != 0x20) {
memcpy(&raw[32], &der[pos + 3], 32);
} else {
memcpy(&raw[32], &der[pos + 2], 32);
}
memcpy(raw_rs, raw, sizeof(raw));
return 1;
}

View File

@ -1,298 +0,0 @@
/**
* \file tuya_ble_config.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_CONFIG_H__
#define TUYA_BLE_CONFIG_H__
#if defined(CUSTOMIZED_TUYA_BLE_CONFIG_FILE)
#include CUSTOMIZED_TUYA_BLE_CONFIG_FILE
#endif
/*
* If the application has a customized production test project(file),please define CUSTOMIZED_TUYA_BLE_APP_PRODUCT_TEST_FILE in CUSTOMIZED_TUYA_BLE_CONFIG_FILE.
*/
#ifndef CUSTOMIZED_TUYA_BLE_APP_PRODUCT_TEST_HEADER_FILE
#undef CUSTOMIZED_TUYA_BLE_APP_PRODUCT_TEST_HEADER_FILE
#endif
/*
* If needed,please define CUSTOMIZED_TUYA_BLE_APP_UART_COMMON_FILE in CUSTOMIZED_TUYA_BLE_CONFIG_FILE.
*/
#ifndef CUSTOMIZED_TUYA_BLE_APP_UART_COMMON_HEADER_FILE
#undef CUSTOMIZED_TUYA_BLE_APP_UART_COMMON_HEADER_FILE
#endif
/*
* If needed,please define TUYA_BLE_PORT_PLATFORM_HEADER_FILE in CUSTOMIZED_TUYA_BLE_CONFIG_FILE.
*/
#ifndef TUYA_BLE_PORT_PLATFORM_HEADER_FILE
#undef TUYA_BLE_PORT_PLATFORM_HEADER_FILE
#endif
/*
* If using an OS, be sure to call the tuya api functions and SDK-related queues within the same task
*/
#ifndef TUYA_BLE_USE_OS
#define TUYA_BLE_USE_OS 1
#endif
/*
* If using an OS, tuya ble sdk will create a task autonomously to process ble event.
*/
#if TUYA_BLE_USE_OS
#ifndef TUYA_BLE_SELF_BUILT_TASK
#define TUYA_BLE_SELF_BUILT_TASK 1
#endif
#if TUYA_BLE_SELF_BUILT_TASK
#ifndef TUYA_BLE_TASK_PRIORITY
#define TUYA_BLE_TASK_PRIORITY 1
#endif
#ifndef TUYA_BLE_TASK_STACK_SIZE
#define TUYA_BLE_TASK_STACK_SIZE 256 * 10 //!< Task stack size application do not change this default value
#endif
#endif
#endif
/*
* TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_BLE ble normal
* TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_REGISTER_FROM_BLE device register from ble
* TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_MESH ble mesh
* TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_WIFI_24G wifi_2.4g
* TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_WIFI_5G wifi_5g
* TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_ZIGBEE zigbee
* TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_NB nb-iot
* @note:
* for example (TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_BLE|TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_MESH|TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_WIFI_24G)
*/
//#define TUYA_BLE_DEVICE_COMMUNICATION_ABILITY (TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_BLE|TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_WIFI_24G|TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_WIFI_5G)
#ifndef TUYA_BLE_DEVICE_COMMUNICATION_ABILITY
#define TUYA_BLE_DEVICE_COMMUNICATION_ABILITY (TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_BLE|TUYA_BLE_DEVICE_COMMUNICATION_ABILITY_REGISTER_FROM_BLE)
#endif
/*
* Whether it is a shared device.
*/
#ifndef TUYA_BLE_DEVICE_SHARED
#define TUYA_BLE_DEVICE_SHARED 0
#endif
/*
* If it is 1, then sdk need to perform the unbind operation,otherwise sdk do not need.
*/
#ifndef TUYA_BLE_DEVICE_UNBIND_MODE
#define TUYA_BLE_DEVICE_UNBIND_MODE 1
#endif
/*
* If TUYA_BLE_WIFI_DEVICE_REGISTER_MODE is 1,Mobile app must first sends instructions to query network status after sending the pairing request .
*/
#ifndef TUYA_BLE_WIFI_DEVICE_REGISTER_MODE
#define TUYA_BLE_WIFI_DEVICE_REGISTER_MODE 1
#endif
/*
* if 1 ,tuya ble sdk authorization self-management
*/
#ifndef TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT
#define TUYA_BLE_DEVICE_AUTH_SELF_MANAGEMENT 1
#endif
/*
* TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY encrypt with auth key
* TUYA_BLE_SECURE_CONNECTION_WITH_ECC encrypt with ECDH
* TUYA_BLE_SECURE_CONNECTION_WTIH_PASSTHROUGH no encrypt
* TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY_ADVANCED_ENCRYPTION advanced encrypt(security chip ) with auth key
* @note : only choose one
*/
#ifndef TUYA_BLE_SECURE_CONNECTION_TYPE
#define TUYA_BLE_SECURE_CONNECTION_TYPE TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY
#endif
/*
* MACRO for advanced encryption,if 1 will perform two-way authentication on every connection,otherwise perform certification at the first registration.
*/
#if (TUYA_BLE_SECURE_CONNECTION_TYPE==TUYA_BLE_SECURE_CONNECTION_WITH_AUTH_KEY_ADVANCED_ENCRYPTION)
#ifndef TUYA_BLE_ADVANCED_ENCRYPTION_AUTH_ON_CONNECT
#define TUYA_BLE_ADVANCED_ENCRYPTION_AUTH_ON_CONNECT 0
#endif
#ifndef TUYA_BLE_INCLUDE_CJSON_COMPONENTS
#define TUYA_BLE_INCLUDE_CJSON_COMPONENTS 1
#endif
#endif
/*
* if 1 ,ble sdk will update mac address with with the address of the authorization information.
*/
#ifndef TUYA_BLE_DEVICE_MAC_UPDATE
#define TUYA_BLE_DEVICE_MAC_UPDATE 0
#endif
/*
* if 1 ,after update mac will reset.
*/
#ifndef TUYA_BLE_DEVICE_MAC_UPDATE_RESET
#define TUYA_BLE_DEVICE_MAC_UPDATE_RESET 0
#endif
/*
* if defined ,ble sdk use platform memory heap.
*/
#ifndef TUYA_BLE_USE_PLATFORM_MEMORY_HEAP
#define TUYA_BLE_USE_PLATFORM_MEMORY_HEAP 0
#endif
/*
* if defined ,include UART module
*/
//#define TUYA_BLE_UART
/*
* if defined ,include product test module
*/
//#define TUYA_BLE_PRODUCTION_TEST
/*
* gatt mtu max sizes
*/
#ifndef TUYA_BLE_DATA_MTU_MAX
#define TUYA_BLE_DATA_MTU_MAX 243
#endif
/*
* if defined ,enable sdk log output
*/
#ifndef TUYA_BLE_LOG_ENABLE
#define TUYA_BLE_LOG_ENABLE 1
#endif
#ifndef TUYA_BLE_LOG_COLORS_ENABLE
#define TUYA_BLE_LOG_COLORS_ENABLE 0
#endif
#ifndef TUYA_BLE_LOG_LEVEL
#define TUYA_BLE_LOG_LEVEL TUYA_BLE_LOG_LEVEL_DEBUG
#endif
/*
* if defined ,enable app log output
*/
#ifndef TUYA_APP_LOG_ENABLE
#define TUYA_APP_LOG_ENABLE 1
#endif
#ifndef TUYA_APP_LOG_COLORS_ENABLE
#define TUYA_APP_LOG_COLORS_ENABLE 0
#endif
#ifndef TUYA_APP_LOG_LEVEL
#define TUYA_APP_LOG_LEVEL TUYA_APP_LOG_LEVEL_DEBUG
#endif
/*
* If it is 1, then sdk need to request beacon key from app when binding .
*/
#ifndef TUYA_BLE_BEACON_KEY_ENABLE
#define TUYA_BLE_BEACON_KEY_ENABLE 0
#endif
/*
* Enable the weather module.
*/
#ifndef TUYA_BLE_FEATURE_WEATHER_ENABLE
#define TUYA_BLE_FEATURE_WEATHER_ENABLE 0
#endif
/*
* Enable support the link layer encryption.
*/
#ifndef TUYA_BLE_LINK_LAYER_ENCRYPTION_SUPPORT_ENABLE
#define TUYA_BLE_LINK_LAYER_ENCRYPTION_SUPPORT_ENABLE 0
#endif
/*
* Whether to automatically perform a time request after the connection is established.
* - 0 Not request.
* - 1 Request cloud time.
* - 2 Request phone local time.
*/
#ifndef TUYA_BLE_AUTO_REQUEST_TIME_CONFIGURE
#define TUYA_BLE_AUTO_REQUEST_TIME_CONFIGURE 1
#endif
//nv
/* The minimum size of flash erasure. May be a flash sector size. */
#ifndef TUYA_NV_ERASE_MIN_SIZE
#define TUYA_NV_ERASE_MIN_SIZE (0x100)
#endif
/* the flash write granularity, unit: byte*/
#ifndef TUYA_NV_WRITE_GRAN
#define TUYA_NV_WRITE_GRAN (4)
#endif
/* start address */
#ifndef TUYA_NV_START_ADDR
#define TUYA_NV_START_ADDR 0
#endif
/* area size. */
#ifndef TUYA_NV_AREA_SIZE
#define TUYA_NV_AREA_SIZE (4*TUYA_NV_ERASE_MIN_SIZE)
#endif
/*MACRO for production test module*/
#ifndef TUYA_BLE_APP_VERSION_STRING
#define TUYA_BLE_APP_VERSION_STRING "1.0"
#endif
#ifndef TUYA_BLE_APP_BUILD_FIRMNAME_STRING
#define TUYA_BLE_APP_BUILD_FIRMNAME_STRING "tuya_ble_sdk_app_demo_xxx"
#endif
#ifndef TUYA_BLE_APP_FIRMWARE_KEY
#define TUYA_BLE_APP_FIRMWARE_KEY ""
#endif
#endif

View File

@ -1,38 +0,0 @@
/**
* \file tuya_ble_sdk_version.h
*
* \brief
*/
/*
* Copyright (C) 2014-2019, Tuya Inc., All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of tuya ble sdk
*/
#ifndef TUYA_BLE_SDK_VERSION_H__
#define TUYA_BLE_SDK_VERSION_H__
#define TUYA_BLE_SDK_VERSION_NUM 0x020000
#define TUYA_BLE_SDK_VERSION_STR "2.0.0"
#endif