Commit be59c2bf authored by 黄振令's avatar 黄振令

【修改内容】增加ota功能,platform那层未完成

【提交人】huang.zhenling
parent 7d63f2f6
......@@ -27,10 +27,12 @@ int _kk_sendto_cloud(cJSON *root)
pTopic = cJSON_GetObjectItem(root, "topic");
if(pTopic == NULL){
printf("[%s][%d] topic is null \n",__FUNCTION__,__LINE__);
return;
}
pData = cJSON_GetObjectItem(root, "payload");
if(pData == NULL){
printf("[%s][%d] payload is null \n",__FUNCTION__,__LINE__);
return;
}
printf("[%s][%d] topic:%s\n",__FUNCTION__,__LINE__,pTopic->valuestring);
......@@ -46,6 +48,7 @@ void KK_Data_FromDev(void* str,int len)
}
root=cJSON_Parse((char*)str);
if(root == NULL){
printf("[%s][%d] root is null \n",__FUNCTION__,__LINE__);
return;
}
cmd = cJSON_GetObjectItem(root, "cmd");
......
......@@ -6,6 +6,8 @@
#include "cJSON.h"
const char KK_URI_SYS_PREFIX[] = "/sys/%s/%s/#";
const char KK_URI_OTA_PREFIX[] = "/ota/device/upgrade/%s/%s/#";
int KK_Subdev_Subscribe(const cJSON *root)
{
......@@ -28,14 +30,20 @@ int KK_Subdev_Subscribe(const cJSON *root)
if(productCode == NULL){
return -1;
}
url_len = strlen(KK_URI_SYS_PREFIX) + strlen(productType->valuestring) + strlen(productCode->valuestring) + 1;
url_len = strlen(KK_URI_OTA_PREFIX) + strlen(productType->valuestring) + strlen(productCode->valuestring) + 1;
char *url = malloc(url_len);
if (url == NULL) {
return -1;
}
memset(url, 0, url_len);
snprintf(url, url_len, KK_URI_OTA_PREFIX, productType->valuestring, productCode->valuestring);
printf("ota [%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);
res = KK_MQTT_SubTopic(url);
memset(url, 0, url_len);
snprintf(url, url_len, KK_URI_SYS_PREFIX, productType->valuestring, productCode->valuestring);
printf("[%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);
printf("sys [%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);
res = KK_MQTT_SubTopic(url);
free(url);
return res;
......@@ -48,15 +56,21 @@ static int _kk_client_subscribe(char productType[PRODUCT_TYPE_LEN], char product
int url_len = 0;
printf("[%s][%d] \n",__FUNCTION__,__LINE__);
url_len = strlen(KK_URI_SYS_PREFIX) + strlen(productType) + strlen(productCode) + 1;
url_len = strlen(KK_URI_OTA_PREFIX) + strlen(productType) + strlen(productCode) + 1;
char *url = malloc(url_len);
if (url == NULL) {
return -1;
}
memset(url, 0, url_len);
snprintf(url, url_len, KK_URI_OTA_PREFIX, productType, productCode);
printf("ota [%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);
res = KK_MQTT_SubTopic(url);
memset(url, 0, url_len);
snprintf(url, url_len, KK_URI_SYS_PREFIX, productType, productCode);
printf("[%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);
printf("sys [%s][%d] URL:%s\n",__FUNCTION__,__LINE__,url);
res = KK_MQTT_SubTopic(url);
......
......@@ -352,16 +352,23 @@ void HAL_ThreadDelete(_IN_ void *thread_handle)
pthread_join((pthread_t)thread_handle, 0);
}
}
#if 0
#if 1
static FILE *fp;
#define otafilename "/tmp/alinkota.bin"
#define otafilename "/tmp/kkota.bin"
#define __DEMO__
void HAL_Firmware_Persistence_Start(void)
void HAL_Firmware_Persistence_Start(void* fileName)
{
#ifdef __DEMO__
fp = fopen(otafilename, "w");
char * file = NULL;
if (fileName == NULL){
file = otafilename;
}else{
file = fileName;
}
fp = fopen(file, "w");
// assert(fp);
#endif
return;
......
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include "infra_config.h"
static uint64_t _linux_get_time_ms(void)
{
struct timeval tv = { 0 };
uint64_t time_ms;
gettimeofday(&tv, NULL);
time_ms = tv.tv_sec * 1000 + tv.tv_usec / 1000;
return time_ms;
}
static uint64_t _linux_time_left(uint64_t t_end, uint64_t t_now)
{
uint64_t t_left;
if (t_end > t_now) {
t_left = t_end - t_now;
} else {
t_left = 0;
}
return t_left;
}
uintptr_t HAL_TCP_Establish(const char *host, uint16_t port)
{
struct addrinfo hints;
struct addrinfo *addrInfoList = NULL;
struct addrinfo *cur = NULL;
int fd = 0;
int rc = 0;
char service[6];
uint8_t dns_retry = 0;
memset(&hints, 0, sizeof(hints));
printf("establish tcp connection with server(host='%s', port=[%u])\n", host, port);
hints.ai_family = AF_INET; /* only IPv4 */
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
sprintf(service, "%u", port);
while(dns_retry++ < 8) {
rc = getaddrinfo(host, service, &hints, &addrInfoList);
if (rc != 0) {
printf("getaddrinfo error[%d], res: %s, host: %s, port: %s\n", dns_retry, gai_strerror(rc), host, service);
sleep(1);
continue;
}else{
break;
}
}
if (rc != 0) {
printf("getaddrinfo error(%d), host = '%s', port = [%d]\n", rc, host, port);
return (uintptr_t)(-1);
}
for (cur = addrInfoList; cur != NULL; cur = cur->ai_next) {
if (cur->ai_family != AF_INET) {
printf("socket type error\n");
rc = -1;
continue;
}
fd = socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
if (fd < 0) {
printf("create socket error\n");
rc = -1;
continue;
}
if (connect(fd, cur->ai_addr, cur->ai_addrlen) == 0) {
rc = fd;
break;
}
close(fd);
printf("connect error\n");
rc = -1;
}
if (-1 == rc) {
printf("fail to establish tcp\n");
} else {
printf("success to establish tcp, fd=%d\n", rc);
}
freeaddrinfo(addrInfoList);
return (uintptr_t)rc;
}
int HAL_TCP_Destroy(uintptr_t fd)
{
int rc;
/* Shutdown both send and receive operations. */
rc = shutdown((int) fd, 2);
if (0 != rc) {
printf("shutdown error\n");
return -1;
}
rc = close((int) fd);
if (0 != rc) {
printf("closesocket error\n");
return -1;
}
return 0;
}
int32_t HAL_TCP_Write(uintptr_t fd, const char *buf, uint32_t len, uint32_t timeout_ms)
{
int ret,tcp_fd;
uint32_t len_sent;
uint64_t t_end, t_left;
fd_set sets;
int net_err = 0;
t_end = _linux_get_time_ms() + timeout_ms;
len_sent = 0;
ret = 1; /* send one time if timeout_ms is value 0 */
if (fd >= FD_SETSIZE) {
return -1;
}
tcp_fd = (int)fd;
do {
t_left = _linux_time_left(t_end, _linux_get_time_ms());
if (0 != t_left) {
struct timeval timeout;
FD_ZERO(&sets);
FD_SET(tcp_fd, &sets);
timeout.tv_sec = t_left / 1000;
timeout.tv_usec = (t_left % 1000) * 1000;
ret = select(tcp_fd + 1, NULL, &sets, NULL, &timeout);
if (ret > 0) {
if (0 == FD_ISSET(tcp_fd, &sets)) {
printf("Should NOT arrive\n");
/* If timeout in next loop, it will not sent any data */
ret = 0;
continue;
}
} else if (0 == ret) {
printf("select-write timeout %d\n", tcp_fd);
break;
} else {
if (EINTR == errno) {
printf("EINTR be caught\n");
continue;
}
printf("select-write fail, ret = select() = %d\n", ret);
net_err = 1;
break;
}
}
if (ret > 0) {
ret = send(tcp_fd, buf + len_sent, len - len_sent, 0);
if (ret > 0) {
len_sent += ret;
} else if (0 == ret) {
printf("No data be sent\n");
} else {
if (EINTR == errno) {
printf("EINTR be caught\n");
continue;
}
printf("send fail, ret = send() = %d\n", ret);
net_err = 1;
break;
}
}
} while (!net_err && (len_sent < len) && (_linux_time_left(t_end, _linux_get_time_ms()) > 0));
if (net_err) {
return -1;
} else {
return len_sent;
}
}
int32_t HAL_TCP_Read(uintptr_t fd, char *buf, uint32_t len, uint32_t timeout_ms)
{
int ret, err_code, tcp_fd;
uint32_t len_recv;
uint64_t t_end, t_left;
fd_set sets;
struct timeval timeout;
t_end = _linux_get_time_ms() + timeout_ms;
len_recv = 0;
err_code = 0;
if (fd >= FD_SETSIZE) {
return -1;
}
tcp_fd = (int)fd;
do {
t_left = _linux_time_left(t_end, _linux_get_time_ms());
if (0 == t_left) {
break;
}
FD_ZERO(&sets);
FD_SET(tcp_fd, &sets);
timeout.tv_sec = t_left / 1000;
timeout.tv_usec = (t_left % 1000) * 1000;
ret = select(tcp_fd + 1, &sets, NULL, NULL, &timeout);
if (ret > 0) {
ret = recv(tcp_fd, buf + len_recv, len - len_recv, 0);
if (ret > 0) {
len_recv += ret;
} else if (0 == ret) {
printf("connection is closed\n");
err_code = -1;
break;
} else {
if (EINTR == errno) {
continue;
}
printf("recv fail\n");
err_code = -2;
break;
}
} else if (0 == ret) {
break;
} else {
if (EINTR == errno) {
continue;
}
printf("select-recv fail\n");
err_code = -2;
break;
}
} while ((len_recv < len));
/* priority to return data bytes if any data be received from TCP connection. */
/* It will get error code on next calling */
return (0 != len_recv) ? len_recv : err_code;
}
/*
*
*/
//#include "../dm/iotx_dm_internal.h"
#include "dm_fota.h"
#include "../ota/ota_api.h"
#define dm_log_err printf
#define dm_log_debug printf
#define dm_log_info printf
static dm_fota_ctx_t g_dm_fota_ctx;
static dm_fota_ctx_t *_dm_fota_get_ctx(void)
{
return &g_dm_fota_ctx;
}
int dm_fota_init(void)
{
dm_fota_ctx_t *ctx = _dm_fota_get_ctx();
memset(ctx, 0, sizeof(dm_fota_ctx_t));
return SUCCESS_RETURN;
}
int dm_fota_deinit(void)
{
dm_fota_ctx_t *ctx = _dm_fota_get_ctx();
memset(ctx, 0, sizeof(dm_fota_ctx_t));
return SUCCESS_RETURN;
}
static int _dm_fota_send_new_config_to_user(void *ota_handle)
{
int res = 0, message_len = 0;
char *message = NULL;
char version[128] = {0};
const char *fota_new_config_fmt = "{\"version\":\"%s\"}";
IOT_OTA_Ioctl(ota_handle, IOT_OTAG_VERSION, version, 128);
message_len = strlen(fota_new_config_fmt) + strlen(version) + 1;
message = malloc(message_len);
if (message == NULL) {
return MEMORY_NOT_ENOUGH;
}
memset(message, 0, message_len);
HAL_Snprintf(message, message_len, fota_new_config_fmt, version);
dm_log_info("Send To User: %s", message);
//res = _dm_msg_send_to_user(IOTX_DM_EVENT_FOTA_NEW_FIRMWARE, message);
if (res != SUCCESS_RETURN) {
if (message) {
free(message);
}
return FAIL_RETURN;
}
return SUCCESS_RETURN;
}
int dm_fota_perform_sync(_OU_ char *output, _IN_ int output_len)
{
int res = 0, file_download = 0;
uint32_t file_size = 0, file_downloaded = 0;
uint64_t percent_pre = 0, percent_now = 0;
unsigned long long report_pre = 0, report_now = 0;
dm_fota_ctx_t *ctx = _dm_fota_get_ctx();
void *ota_handle = NULL;
uint32_t ota_type = IOT_OTAT_NONE;
int ret = 0;
if (output == NULL || output_len <= 0) {
return INVALID_PARAMETER;
}
/* Get Ota Handle */
res = dm_ota_get_ota_handle(&ota_handle);
if (res != SUCCESS_RETURN) {
return FAIL_RETURN;
}
if (ota_handle == NULL) {
return FAIL_RETURN;
}
IOT_OTA_Ioctl(ota_handle, IOT_OTAG_OTA_TYPE, &ota_type, 4);
if (ota_type != IOT_OTAT_FOTA) {
return FAIL_RETURN;
}
/* reset the size_fetched in ota_handle to be 0 */
IOT_OTA_Ioctl(ota_handle, IOT_OTAG_RESET_FETCHED_SIZE, ota_handle, 4);
/* Prepare Write Data To Storage */
HAL_Firmware_Persistence_Start(NULL);
while (1) {
file_download = IOT_OTA_FetchYield(ota_handle, output, output_len, 1);
if (file_download < 0) {
IOT_OTA_ReportProgress(ota_handle, IOT_OTAP_FETCH_FAILED, NULL);
HAL_Firmware_Persistence_Stop();
ctx->is_report_new_config = 0;
return FAIL_RETURN;
}
/* Write Config File Into Stroage */
ret = HAL_Firmware_Persistence_Write(output, file_download);
if (-1 == ret) {
IOT_OTA_ReportProgress(ota_handle, IOT_OTAP_BURN_FAILED, NULL);
dm_log_err("Fota write firmware failed");
HAL_Firmware_Persistence_Stop();
ctx->is_report_new_config = 0;
return FAIL_RETURN;
}
/* Get OTA information */
IOT_OTA_Ioctl(ota_handle, IOT_OTAG_FETCHED_SIZE, &file_downloaded, 4);
IOT_OTA_Ioctl(ota_handle, IOT_OTAG_FILE_SIZE, &file_size, 4);
/* Calculate Download Percent And Update Report Timestamp*/
percent_now = (file_downloaded * 100) / file_size;
report_now = HAL_UptimeMs();
/* Report Download Process To Cloud */
if (report_now < report_pre) {
report_pre = report_now;
}
if ((((percent_now - percent_pre) > 5) &&
((report_now - report_pre) > 50)) || (percent_now >= IOT_OTAP_FETCH_PERCENTAGE_MAX)) {
IOT_OTA_ReportProgress(ota_handle, percent_now, NULL);
percent_pre = percent_now;
report_pre = report_now;
}
/* Check If OTA Finished */
if (IOT_OTA_IsFetchFinish(ota_handle)) {
uint32_t file_isvalid = 0;
IOT_OTA_Ioctl(ota_handle, IOT_OTAG_CHECK_FIRMWARE, &file_isvalid, 4);
if (file_isvalid == 0) {
HAL_Firmware_Persistence_Stop();
IOT_OTA_ReportProgress(ota_handle, IOT_OTAP_CHECK_FALIED, NULL);
ctx->is_report_new_config = 0;
return FAIL_RETURN;
} else {
break;
}
}
}
HAL_Firmware_Persistence_Stop();
ctx->is_report_new_config = 0;
return SUCCESS_RETURN;
}
int dm_fota_status_check(void)
{
int res = 0;
dm_fota_ctx_t *ctx = _dm_fota_get_ctx();
void *ota_handle = NULL;
/* Get Ota Handle */
res = dm_ota_get_ota_handle(&ota_handle);
if (res != SUCCESS_RETURN) {
return FAIL_RETURN;
}
if (IOT_OTA_IsFetching(ota_handle)) {
uint32_t ota_type = IOT_OTAT_NONE;
IOT_OTA_Ioctl(ota_handle, IOT_OTAG_OTA_TYPE, &ota_type, 4);
if (ota_type == IOT_OTAT_FOTA) {
/* Send New Config Information To User */
if (ctx->is_report_new_config == 0) {
dm_log_debug("Fota Status Check");
res = _dm_fota_send_new_config_to_user(ota_handle);
if (res == SUCCESS_RETURN) {
ctx->is_report_new_config = 1;
}
}
}
}
return SUCCESS_RETURN;
}
int dm_fota_request_image(const char *version, int buffer_len)
{
int res = 0;
void *ota_handle = NULL;
char *version_str = NULL;
if (NULL == version || buffer_len <= 0) {
dm_log_info("invalid input");
return FAIL_RETURN;
}
/* Get Ota Handle */
res = dm_ota_get_ota_handle(&ota_handle);
if (res != SUCCESS_RETURN) {
return FAIL_RETURN;
}
version_str = malloc(buffer_len + 1);
if (NULL == version_str) {
dm_log_info("failed to malloc");
return FAIL_RETURN;
}
memset(version_str, 0, buffer_len + 1);
memcpy(version_str, version, buffer_len);
res = iotx_req_image(ota_handle, version_str);
free(version_str);
return res;
}
/*
*
*/
#ifndef _DM_FOTA_H_
#define _DM_FOTA_H_
#include "kk_tsl_common.h"
typedef struct {
int is_report_new_config;
} dm_fota_ctx_t;
int dm_fota_init(void);
int dm_fota_deinit(void);
int dm_fota_perform_sync(_OU_ char *output, _IN_ int output_len);
int dm_fota_status_check(void);
int dm_fota_request_image(_IN_ const char *version, _IN_ int buffer_len);
#endif
/*
*
*/
#include "iotx_ota_internal.h"
#include "dm_ota.h"
#include "cJSON.h"
#include "kk_dm_api.h"
static dm_ota_ctx_t g_dm_ota_ctx;
static dm_ota_ctx_t *_dm_ota_get_ctx(void)
{
return &g_dm_ota_ctx;
}
int dm_ota_init(void)
{
dm_ota_ctx_t *ctx = _dm_ota_get_ctx();
memset(ctx, 0, sizeof(dm_ota_ctx_t));
HAL_GetProduct_Type(ctx->product_key);
HAL_GetProduct_Code(ctx->device_name);
return SUCCESS_RETURN;
}
int dm_ota_sub(void)
{
dm_ota_ctx_t *ctx = _dm_ota_get_ctx();
void *handle = NULL;
/* Init OTA Handle */
handle = IOT_OTA_Init(ctx->product_key, ctx->device_name, NULL);
if (handle == NULL) {
return FAIL_RETURN;
}
ctx->ota_handle = handle;
return SUCCESS_RETURN;
}
int ota_uri_parse_pkdn(_IN_ char *uri, _IN_ int uri_len, _IN_ int start_deli, _IN_ int end_deli,
_OU_ char product_key[PRODUCT_KEY_MAXLEN], _OU_ char device_name[DEVICE_NAME_MAXLEN])
{
int res = 0, start = 0, end = 0, slice = 0;
int item_index = 0;
int count = 0;
if (uri == NULL || uri_len <= 0 || product_key == NULL || device_name == NULL ||
(strlen(product_key) >= PRODUCT_KEY_MAXLEN) || (strlen(device_name) >= DEVICE_NAME_MAXLEN)) {
return INVALID_PARAMETER;
}
for (item_index = 0; item_index < uri_len; item_index++) {
if (uri[item_index] == '/' && (item_index + 1) < uri_len) {
count++;
if (count == start_deli) {
start = item_index;
}else if (count == start_deli + 1){
slice = item_index;
}else if (count == end_deli){
end = item_index;
}
}
}
if (end == 0){
end = item_index;
}
/* dm_log_debug("URI Product Key: %.*s, Device Name: %.*s", slice - start - 1, uri + start + 1, end - slice - 1,
uri + slice + 1); */
memcpy(product_key, uri + start + 1, slice - start - 1);
memcpy(device_name, uri + slice + 1, end - slice - 1);
return SUCCESS_RETURN;
}
int dm_ota_setPKN(void* topic)
{
dm_ota_ctx_t *ctx = _dm_ota_get_ctx();
char product_key[PRODUCT_KEY_MAXLEN] = {0};
char device_name[DEVICE_NAME_MAXLEN] = {0};
int res = 0;
//ota topic:/ota/device/upgrade/{product_key}/{device_name}
res =ota_uri_parse_pkdn((char *)topic, strlen(topic), 4, 6, product_key,
device_name);
if (res != SUCCESS_RETURN) {
printf("dm_ota_setPKN error \n");
return FAIL_RETURN;
}
memset(ctx->product_key, 0, PRODUCT_KEY_MAXLEN);
memset(ctx->device_name, 0, DEVICE_NAME_MAXLEN);
memcpy(ctx->product_key, product_key, PRODUCT_KEY_MAXLEN);
memcpy(ctx->device_name, device_name, DEVICE_NAME_MAXLEN);
return SUCCESS_RETURN;
}
int dm_ota_deinit(void)
{
dm_ota_ctx_t *ctx = _dm_ota_get_ctx();
if (ctx->ota_handle) {
IOT_OTA_Deinit(ctx->ota_handle);
ctx->ota_handle = NULL;
}
return SUCCESS_RETURN;
}
#if 0
int dm_ota_switch_device(int devid)
{
char pk[PRODUCT_KEY_MAXLEN] = {0};
char dn[DEVICE_NAME_MAXLEN] = {0};
char ds[DEVICE_SECRET_MAXLEN] = {0};
int ret = dm_mgr_search_device_by_devid(devid, pk, dn, ds);
void *ota_handle = NULL;
int res = -1;
dm_ota_ctx_t *ctx = NULL;
if (SUCCESS_RETURN != ret) {
dm_log_err("could not find device by id, ret is %d", ret);
return FAIL_RETURN;
}
dm_log_info("do subdevice ota, pk, dn is %s, %s", pk, dn);
ota_handle = NULL;
res = dm_ota_get_ota_handle(&ota_handle);
if (res != SUCCESS_RETURN) {
return FAIL_RETURN;
}
/* if currently a device is doing OTA, do not interrupt */
if (IOT_OTA_IsFetching(ota_handle)) {
dm_log_info("OTA is processing, can not switch to another device");
return FAIL_RETURN;
}
dm_ota_deinit();
ctx = _dm_ota_get_ctx();
memset(ctx, 0, sizeof(dm_ota_ctx_t));
memcpy(ctx->product_key, pk, strlen(pk) + 1);
memcpy(ctx->device_name, dn, strlen(dn) + 1);
ret = dm_ota_sub();
if (ret < 0) {
dm_log_err("dm_ota_sub ret is %d, %s, %s\n", ret, pk, dn);
}
return ret;
}
#endif
int dm_ota_get_ota_handle(void **handle)
{
dm_ota_ctx_t *ctx = _dm_ota_get_ctx();
if (handle == NULL || *handle != NULL) {
return FAIL_RETURN;
}
if (ctx->ota_handle == NULL) {
return FAIL_RETURN;
}
*handle = ctx->ota_handle;
return SUCCESS_RETURN;
}
void dm_ota_handle(void *data){
printf("dm_ota_handle ================== [%s]\n",data);
char *out;
int res = 0;
cJSON *json;
cJSON *topic;
cJSON *payload;
json=cJSON_Parse(data);
if (!json) {
printf("Error before: [%s]\n","cJSON_Parse");
}
else{
topic = cJSON_GetObjectItem(json, "topic");
payload = cJSON_GetObjectItem(json, "payload");
printf("topic: [%s] ,payload= %s \n",topic->valuestring,payload->valuestring );
if (strstr(topic->valuestring, "/ota/device/upgrade") != NULL){
char buf[128] = {0};
int len = 128;
if (dm_ota_check(payload->valuestring, strlen(payload->valuestring)+1, IOTX_OTA_TOPIC_TYPE_DEVICE_UPGRATE) == 0){
dm_ota_setPKN(topic->valuestring);
dm_fota_perform_sync(buf, len);
}else{
printf("parse params error !! \n");
}
}else {
printf("invaild ota topic: [%s]\n", topic->valuestring);
}
cJSON_Delete(json);
}
}
int dm_ota_check(void* payload, int len, iotx_ota_topic_types_t type){
void *ota_handle = NULL;
void* otaHandle = NULL;
dm_ota_get_ota_handle(&otaHandle);
return ota_callback(otaHandle, payload, len,type);
}
int dm_ota_yield(int timeout_ms)
{
void *data = NULL;
int count = 0;
if (timeout_ms <= 0) {
return INVALID_PARAMETER;
}
while (CONFIG_DISPATCH_QUEUE_MAXLEN == 0 || count++ < CONFIG_DISPATCH_QUEUE_MAXLEN) {
if (dm_queue_msg_next3(&data) == SUCCESS_RETURN) {
//dm_queue_msg_t *msg = (dm_queue_msg_t *)data;
printf("dm_ota_yield call \n");
dm_ota_handle(data);
free(data);
data = NULL;
} else {
break;
}
}
usleep(timeout_ms*1000);
return SUCCESS_RETURN;
}
/*
*
*/
#ifndef _DM_OTA_H_
#define _DM_OTA_H_
#include "kk_tsl_common.h"
typedef struct {
void *ota_handle;
char product_key[PRODUCT_KEY_MAXLEN];
char device_name[DEVICE_NAME_MAXLEN];
} dm_ota_ctx_t;
int dm_ota_init(void);
int dm_ota_sub(void);
int dm_ota_deinit(void);
int dm_ota_get_ota_handle(void **handle);
int dm_ota_switch_device(int devid);
#endif
......@@ -8,6 +8,8 @@
#include "kk_tsl_common.h"
#include "kk_dm_mng.h"
#include "com_api.h"
#include "dm_ota.h"
static dm_api_ctx_t g_dm_api_ctx;
......@@ -96,7 +98,7 @@ int iotx_dm_subdev_topo_del(_IN_ int devid)
int res = 0;
if (devid < 0) {
return DM_INVALID_PARAMETER;
return INVALID_PARAMETER;
}
_dm_api_lock();
......@@ -128,7 +130,7 @@ int iotx_dm_subdev_logout(_IN_ int devid)
int res = 0;
if (devid < 0) {
return DM_INVALID_PARAMETER;
return INVALID_PARAMETER;
}
_dm_api_lock();
......@@ -198,6 +200,77 @@ int iotx_dm_connect(_IN_ iotx_dm_event_callback cb)
return SUCCESS_RETURN;
}
int iotx_dm_open(void)
{
int res = 0;
dm_api_ctx_t *ctx = _dm_api_get_ctx();
memset(ctx, 0, sizeof(dm_api_ctx_t));
/* DM Mutex Create*/
ctx->mutex = HAL_MutexCreate();
if (ctx->mutex == NULL) {
return MEMORY_NOT_ENOUGH;
}
/* DM OTA Module Init */
res = dm_ota_init();
if (res != SUCCESS_RETURN) {
goto ERROR;
}
/* DM Cloud Message Parse And Assemble Module Init */
//res = dm_msg_init();
//if (res != SUCCESS_RETURN) {
// goto ERROR;
//}
/* DM QUEUE Module Init */
res = dm_queue_init(CONFIG_DISPATCH_QUEUE_MAXLEN);
if (res != SUCCESS_RETURN) {
return FAIL_RETURN;
}
/* DM Manager Module Init */
res = dm_mgr_init();
if (res != SUCCESS_RETURN) {
goto ERROR;
}
/* DM OTA Module Init */
res = dm_ota_sub();
if (res == SUCCESS_RETURN) {
/* DM Config OTA Module Init */
//dm_cota_init();
/* DM Firmware OTA Mudule Init */
dm_fota_init();
}
return SUCCESS_RETURN;
ERROR:
dm_mgr_deinit();
dm_queue_deinit();
//dm_msg_deinit();
dm_ota_deinit();
if (ctx->mutex) {
HAL_MutexDestroy(ctx->mutex);
}
return FAIL_RETURN;
}
int iotx_dm_subscribe(_IN_ int devid)
{
int res = 0, dev_type = 0;
......@@ -241,4 +314,18 @@ int iotx_dm_subscribe(_IN_ int devid)
return SUCCESS_RETURN;
}
void kk_dm_ota_send(void *data, int len){
dm_queue_msg_insert3(data);
if (data != NULL){
void* buf = malloc(len);
memcpy(buf, data, len);
int res = dm_queue_msg_insert3((void *)buf);
if (res != SUCCESS_RETURN) {
free(buf);
return ;
}
}
}
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*
*/
......
......@@ -356,6 +356,21 @@ int dm_mgr_get_devId_by_mac(_IN_ char device_mac[DEVICE_MAC_MAXLEN],_OU_ int *de
return SUCCESS_RETURN;
}
static void _dm_mgr_destroy_devlist(void)
{
dm_mgr_ctx *ctx = _dm_mgr_get_ctx();
dm_mgr_dev_node_t *del_node = NULL;
dm_mgr_dev_node_t *next_node = NULL;
list_for_each_entry_safe(del_node, next_node, &ctx->dev_list, linked_list, dm_mgr_dev_node_t) {
list_del(&del_node->linked_list);
//dm_shw_destroy(&del_node->dev_shadow);
free(del_node);
}
}
int dm_mgr_init(void)
{
int res = 0;
......@@ -398,6 +413,23 @@ ERROR:
memset(ctx, 0, sizeof(dm_mgr_ctx));
return FAIL_RETURN;
}
int dm_mgr_deinit(void)
{
dm_mgr_ctx *ctx = _dm_mgr_get_ctx();
_dm_mgr_mutex_lock();
_dm_mgr_destroy_devlist();
_dm_mgr_mutex_unlock();
if (ctx->mutex) {
HAL_MutexDestroy(ctx->mutex);
}
return SUCCESS_RETURN;
}
const char DM_MSG_THING_UPSTREAM_REQUEST_PARAMS[] DM_READ_ONLY =
"{\"value\":%s,\"timestamp\":\"%s\"}";
static int _dm_mgr_upstream_request_assemble(_IN_ int msgid, _IN_ int devid, _IN_ const char *service_prefix,
......
......@@ -31,6 +31,15 @@ static void _dm_queue_lock2(void)
}
}
static void _dm_queue_lock3(void)
{
dm_queue_t *ctx = _dm_queue_get_ctx();
if (ctx->mutex3) {
HAL_MutexLock(ctx->mutex3);
}
}
static void _dm_queue_unlock(void)
{
......@@ -47,6 +56,15 @@ static void _dm_queue_unlock2(void)
}
}
static void _dm_queue_unlock3(void)
{
dm_queue_t *ctx = _dm_queue_get_ctx();
if (ctx->mutex3) {
HAL_MutexUnlock(ctx->mutex3);
}
}
int dm_queue_init(int max_size)
{
......@@ -66,11 +84,19 @@ int dm_queue_init(int max_size)
return INVALID_PARAMETER;
}
/* Create Mutex */
ctx->mutex3 = HAL_MutexCreate();
if (ctx->mutex3 == NULL) {
return INVALID_PARAMETER;
}
/* Init List */
ctx->msg_list.max_size = max_size;
INIT_LIST_HEAD(&ctx->msg_list.message_list);
ctx->msg_list2.max_size = max_size;
INIT_LIST_HEAD(&ctx->msg_list2.message_list);
ctx->msg_list3.max_size = max_size;
INIT_LIST_HEAD(&ctx->msg_list3.message_list);
return SUCCESS_RETURN;
}
......@@ -121,6 +147,23 @@ void dm_queue_deinit(void)
free(del_node);
}
del_node = NULL;
next_node = NULL;
del_msg = NULL;
list_for_each_entry_safe(del_node, next_node, &ctx->msg_list3.message_list, linked_list, dm_queue_msg_node_t) {
/* Free Message */
del_msg = (dm_queue_msg_t *)del_node->data;
if (del_msg->data) {
free(del_msg->data);
}
free(del_msg);
del_msg = NULL;
/* Free Node */
list_del(&del_node->linked_list);
free(del_node);
}
}
......@@ -245,3 +288,64 @@ int dm_queue_msg_next2(void **data)
}
int dm_queue_msg_insert3(void *data)
{
dm_queue_t *ctx = _dm_queue_get_ctx();
dm_queue_msg_node_t *node = NULL;
if (data == NULL) {
return INVALID_PARAMETER;
}
_dm_queue_lock3();
printf("dm msg list size: %d, max size: %d", ctx->msg_list3.size, ctx->msg_list3.max_size);
if (ctx->msg_list3.size >= ctx->msg_list3.max_size) {
printf("dm queue list full");
_dm_queue_unlock3();
return FAIL_RETURN;
}
node = malloc(sizeof(dm_queue_msg_node_t));
if (node == NULL) {
_dm_queue_unlock3();
return MEMORY_NOT_ENOUGH;
}
memset(node, 0, sizeof(dm_queue_msg_node_t));
node->data = data;
INIT_LIST_HEAD(&node->linked_list);
ctx->msg_list3.size++;
list_add_tail(&node->linked_list, &ctx->msg_list3.message_list);
_dm_queue_unlock3();
return SUCCESS_RETURN;
}
int dm_queue_msg_next3(void **data)
{
dm_queue_t *ctx = _dm_queue_get_ctx();
dm_queue_msg_node_t *node = NULL;
if (data == NULL || *data != NULL) {
return INVALID_PARAMETER;
}
_dm_queue_lock3();
if (list_empty(&ctx->msg_list3.message_list)) {
_dm_queue_unlock3();
return FAIL_RETURN;
}
node = list_first_entry(&ctx->msg_list3.message_list, dm_queue_msg_node_t, linked_list);
list_del(&node->linked_list);
ctx->msg_list3.size--;
*data = node->data;
free(node);
_dm_queue_unlock3();
return SUCCESS_RETURN;
}
......@@ -29,8 +29,10 @@ typedef struct {
typedef struct {
void *mutex;
void *mutex2;
void *mutex3;
dm_queue_msg_list_t msg_list;
dm_queue_msg_list_t msg_list2;
dm_queue_msg_list_t msg_list3;
} dm_queue_t;
int dm_queue_init(int max_size);
......
......@@ -37,6 +37,8 @@
#define IOTX_LINKKIT_SYNC_DEFAULT_TIMEOUT_MS 10000
#define dm_log_err printf
#define dm_log_debug printf
#define dm_log_info printf
......@@ -228,7 +230,9 @@ static void _iotx_linkkit_event_callback(iotx_dm_event_types_t type, char *data)
printf("_iotx_linkkit_event_callback ================== [%s]\n",data);
char *out;
int res = 0;
cJSON *json, *topic, *payload;
cJSON *json;
cJSON *topic;
cJSON *payload;
json=cJSON_Parse(data);
if (!json) {
......@@ -284,6 +288,10 @@ static void _iotx_linkkit_event_callback(iotx_dm_event_types_t type, char *data)
printf("property set reply \n");
dm_msg_thing_property_set_reply(topic->valuestring, payload->valuestring, strlen(payload->valuestring), NULL);
//kk_tsl_service_property_set(topic->valuestring, payload->valuestring, strlen(payload->valuestring), NULL);
}else if (strstr(topic->valuestring, "/ota/device/upgrade") != NULL){
printf("ota upgrade... \n");
kk_dm_ota_send(data, strlen(data)+1);
}else{
printf("Error 222222222222222 \n");
......@@ -946,9 +954,10 @@ int kk_init_dmproc(){
int res = 0;
iotx_linkkit_ctx_t *ctx = _iotx_linkkit_get_ctx();
/* DM QUEUE Module Init */
res = dm_queue_init(CONFIG_DISPATCH_QUEUE_MAXLEN);
res = iotx_dm_open();
if (res != SUCCESS_RETURN) {
dm_log_err("DM iotx_dm_open Failed");
return FAIL_RETURN;
}
......
......@@ -47,7 +47,8 @@ void mid_cb(void* data, int len){
if (topic != NULL && (strstr(topic->valuestring, "register_reply") != NULL ||
strstr(topic->valuestring, "add_reply") != NULL ||
strstr(topic->valuestring, "login_reply") != NULL ||
strstr(topic->valuestring, "offline_reply") != NULL))
strstr(topic->valuestring, "offline_reply") != NULL ||
strstr(topic->valuestring, "/ota/device/upgrade") != NULL))
{
printf("This topic don't send to platform: %s \r\n", topic->valuestring);
return;
......@@ -158,51 +159,6 @@ void kk_platMsg_dispatch(void)
}
#define MYPORT 5555
#define BUFFER_SIZE 1024
void test_tcp(){
///定义sockfd
int sock_cli = socket(AF_INET,SOCK_STREAM, 0);
///定义sockaddr_in
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(MYPORT); ///服务器端口
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); ///服务器ip
///连接服务器,成功返回0,错误返回-1
if (connect(sock_cli, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0)
{
perror("connect");
exit(1);
}
char sendbuf[BUFFER_SIZE]={0};
char recvbuf[BUFFER_SIZE];
//printf("midd: %s send \r\n", sendbuf);
//send(sock_cli, sendbuf, strlen(sendbuf),0);
while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL)
{
printf("midd: %s send \r\n", sendbuf);
send(sock_cli, sendbuf, strlen(sendbuf),0); ///发送
if(strcmp(sendbuf,"exit\n")==0)
break;
//printf("midd: %s send \r\n", sendbuf);
recv(sock_cli, recvbuf, sizeof(recvbuf),0); ///接收
fputs(recvbuf, stdout);
memset(sendbuf, 0, sizeof(sendbuf));
memset(recvbuf, 0, sizeof(recvbuf));
}
close(sock_cli);
}
time_t getSysTime(){
time_t t;
t = time(NULL);
......@@ -218,7 +174,9 @@ typedef struct {
int subdev_index;
int permit_join;
void *g_mid_dispatch_thread;
void *g_ota_dispatch_thread;
int g_mid_dispatch_thread_running;
int g_ota_dispatch_thread_running;
} mid_ctx_t;
#define MID_YIELD_TIMEOUT_MS (200)
......@@ -241,6 +199,21 @@ void *mid_dispatch_yield(void *args)
return NULL;
}
void *ota_dispatch_yield(void *args)
{
mid_ctx_t *mid_ctx = kk_mid_get_ctx();
while (mid_ctx->g_ota_dispatch_thread_running) {
dm_ota_yield(MID_YIELD_TIMEOUT_MS);
}
return NULL;
}
static int kk_set_product_info(void)
{
HAL_SetProduct_Type(PRODUCT_TPYE);
......@@ -262,7 +235,7 @@ int main(const int argc, const char **argv)
kk_tsl_api_init();
kk_ipc_init(IPC_MID2APP, mid_cb);
kk_ipc_init(IPC_MID2PLAT, mid2p_cb);
dm_mgr_init();
//DB_Init();
//test_tcp();
......@@ -282,6 +255,13 @@ int main(const int argc, const char **argv)
IOT_Linkkit_Close(mid_ctx->master_devid);
return -1;
}
mid_ctx->g_ota_dispatch_thread_running = 1;
res = pthread_create(&mid_ctx->g_ota_dispatch_thread, NULL, ota_dispatch_yield, NULL);
if (res < 0) {
printf("HAL_ThreadCreate Failed\n");
IOT_Linkkit_Close(mid_ctx->master_devid);
return -1;
}
int ct = 0;
for (;;) {
......
This diff is collapsed.
/*
*
*/
#ifndef __IOTX_OTA_H__
#define __IOTX_OTA_H__
int iotx_ota_get_config(void *handle, const char *configScope, const char *getType,
const char *attributeKeys);
int iotx_req_image(void *handle, const char *version);
#endif /* #ifndef __IOTX_OTA_H__ */
/*
*
*/
#ifndef _IOTX_OTA_INTERNAL_H_
#define _IOTX_OTA_INTERNAL_H_
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "infra_httpc.h"
#include "infra_string.h"
#include "infra_md5.h"
#include "infra_sha256.h"
#include "infra_json_parser.h"
#include "ota_api.h"
//#include "iotx_ota_config.h"
//#include "ota_wrapper.h"
#ifdef INFRA_MEM_STATS
#include "infra_mem_stats.h"
#define OTA_MALLOC(size) LITE_malloc(size, MEM_MAGIC, "ota")
#define OTA_FREE(ptr) LITE_free(ptr)
#define OTA_API_MALLOC(size) LITE_malloc(size, MEM_MAGIC, "ota.api")
#define OTA_API_FREE(ptr) LITE_free(ptr)
#else
#define OTA_MALLOC(size) HAL_Malloc(size)
#define OTA_FREE(ptr) {HAL_Free((void *)ptr);ptr = NULL;}
#define OTA_API_MALLOC(size) HAL_Malloc(size)
#define OTA_API_FREE(ptr) {HAL_Free((void *)ptr);ptr = NULL;}
#endif
#define OTA_SNPRINTF HAL_Snprintf
#ifdef INFRA_LOG
#include "infra_log.h"
#define OTA_LOG_CRIT(...) log_crit("ota", __VA_ARGS__)
#define OTA_LOG_ERROR(...) log_err("ota", __VA_ARGS__)
#define OTA_LOG_WRN(...) log_warning("ota", __VA_ARGS__)
#define OTA_LOG_INFO(...) log_info("ota", __VA_ARGS__)
#define OTA_LOG_DEBUG(...) log_debug("ota", __VA_ARGS__)
#else
#define OTA_LOG_CRIT(...) do{HAL_Printf(__VA_ARGS__);HAL_Printf("\r\n");}while(0)
#define OTA_LOG_ERROR(...) do{HAL_Printf(__VA_ARGS__);HAL_Printf("\r\n");}while(0)
#define OTA_LOG_WRN(...) do{HAL_Printf(__VA_ARGS__);HAL_Printf("\r\n");}while(0)
#define OTA_LOG_INFO(...) do{HAL_Printf(__VA_ARGS__);HAL_Printf("\r\n");}while(0)
#define OTA_LOG_DEBUG(...) do{HAL_Printf(__VA_ARGS__);HAL_Printf("\r\n");}while(0)
#endif
typedef enum {
IOTX_OTA_TOPIC_TYPE_DEVICE_REQUEST = 1,
IOTX_OTA_TOPIC_TYPE_DEVICE_UPGRATE = 2,
IOTX_OTA_TOPIC_TYPE_CONFIG_GET = 3,
IOTX_OTA_TOPIC_TYPE_CONFIG_PUSH = 4,
IOTX_OTA_TOPIC_TYPE_MAX
} iotx_ota_topic_types_t;
typedef int (*ota_cb_fpt)(void *pcontext, const char *msg, uint32_t msg_len, iotx_ota_topic_types_t type);
/* is_fetch = 0; start fetch */
/* is_fetch = 1; stop fetch */
typedef void(*ota_fetch_cb_fpt)(void *user_data, int is_fetch, uint32_t size_file, char *purl, char *version);
/* is_fetch = 0; start fetch */
/* is_fetch = 1; stop fetch */
typedef void(*cota_fetch_cb_fpt)(void *user_data, int is_fetch, char *configId, uint32_t configSize, char *sign, \
char *signMethod, char *url, char *getType);
int iotx_ota_set_fetch_callback(void *pt, ota_fetch_cb_fpt fetch_cb, void *user_data);
int iotx_ota_set_cota_fetch_callback(void *pt, cota_fetch_cb_fpt fetch_cb, void *user_data);
const char *otalib_JsonValueOf(const char *json, uint32_t json_len, const char *key, uint32_t *val_len);
void *otalib_MD5Init(void);
void otalib_MD5Update(void *md5, const char *buf, size_t buf_len);
void otalib_MD5Finalize(void *md5, char *output_str);
void otalib_MD5Deinit(void *md5);
void *otalib_Sha256Init(void);
void otalib_Sha256Update(void *sha256, const char *buf, size_t buf_len);
void otalib_Sha256Finalize(void *sha256, char *output_str);
void otalib_Sha256Deinit(void *sha256);
int otalib_GetFirmwareFixlenPara(const char *json_doc,
size_t json_doc_len,
const char *key,
char *dest,
size_t dest_len);
int otalib_GetFirmwareVarlenPara(const char *json_doc,
size_t json_doc_len,
const char *key,
char **dest);
int otalib_GetParams(const char *json_doc, uint32_t json_len, char **url, char **version, char *md5,
uint32_t *file_size);
int otalib_GetConfigParams(const char *json_doc, uint32_t json_len, char **configId, uint32_t *configSize, char **sign,
char **signMethod, char **url, char **getType);
int otalib_GenInfoMsg(char *buf, size_t buf_len, uint32_t id, const char *version);
int otalib_GenReportMsg(char *buf, size_t buf_len, uint32_t id, int progress, const char *msg_detail);
void *ofc_Init(char *url);
int32_t ofc_Fetch(void *handle, char *buf, uint32_t buf_len, uint32_t timeout_s);
int ofc_Deinit(void *handle);
#endif /* _IOTX_OTA_INTERNAL_H_ */
/*
*
*/
#ifndef __OTA_EXPORT_H__
#define __OTA_EXPORT_H__
#include "infra_types.h"
#include "infra_defs.h"
#if defined(__cplusplus)
extern "C" {
#endif
#define OTA_CH_SIGNAL_MQTT (0)
#define OTA_CH_SIGNAL_COAP (1)
#define OTA_CH_FETCH_HTTP (1)
typedef enum {
IOT_OTAE_GENERAL = -1,
IOT_OTAE_INVALID_PARAM = -2,
IOT_OTAE_INVALID_STATE = -3,
IOT_OTAE_STR_TOO_LONG = -4,
IOT_OTAE_FETCH_FAILED = -5,
IOT_OTAE_NOMEM = -6,
IOT_OTAE_OSC_FAILED = -7,
IOT_OTAE_NONE = 0,
} IOT_OTA_Err_t;
/* State of OTA */
typedef enum {
IOT_OTAS_UNINITED = 0, /* Uninitialized State */
IOT_OTAS_INITED, /* Initialized State */
IOT_OTAS_FETCHING, /* Fetching firmware */
IOT_OTAS_FETCHED /* Fetching firmware finish */
} IOT_OTA_State_t;
typedef enum {
IOT_OTAT_NONE,
IOT_OTAT_COTA,
IOT_OTAT_FOTA
} IOT_OTA_Type_t;
/* Progress of OTA */
typedef enum {
/* Burn firmware file failed */
IOT_OTAP_BURN_FAILED = -4,
/* Check firmware file failed */
IOT_OTAP_CHECK_FALIED = -3,
/* Fetch firmware file failed */
IOT_OTAP_FETCH_FAILED = -2,
/* Initialized failed */
IOT_OTAP_GENERAL_FAILED = -1,
/* [0, 100], percentage of fetch progress */
/* The minimum percentage of fetch progress */
IOT_OTAP_FETCH_PERCENTAGE_MIN = 0,
/* The maximum percentage of fetch progress */
IOT_OTAP_FETCH_PERCENTAGE_MAX = 100
} IOT_OTA_Progress_t;
typedef enum {
IOT_OTAG_COTA_CONFIG_ID,
IOT_OTAG_COTA_CONFIG_SIZE,
IOT_OTAG_COTA_SIGN,
IOT_OTAG_COTA_SIGN_METHOD,
IOT_OTAG_COTA_URL,
IOT_OTAG_COTA_GETTYPE,
IOT_OTAG_OTA_TYPE,
IOT_OTAG_FETCHED_SIZE, /* option for get already fetched size */
IOT_OTAG_FILE_SIZE, /* size of file */
IOT_OTAG_MD5SUM, /* md5 in string format */
IOT_OTAG_VERSION, /* version in string format */
IOT_OTAG_CHECK_FIRMWARE, /* Check firmware is valid or not */
IOT_OTAG_CHECK_CONFIG, /* Check config file is valid or not */
IOT_OTAG_RESET_FETCHED_SIZE /* reset the size_fetched parameter to be 0 */
} IOT_OTA_CmdType_t;
/** @defgroup group_api api
* @{
*/
/** @defgroup group_api_ota ota
* @{
*/
/**
* @brief Initialize OTA module, and return handle.
* The MQTT client must be construct before calling this interface.
*
* @param [in] product_key: specify the product key.
* @param [in] device_name: specify the device name.
* @param [in] ch_signal: specify the signal channel.
*
* @retval 0 : Successful.
* @retval -1 : Failed.
* @see None.
*/
void *IOT_OTA_Init(const char *product_key, const char *device_name, void *ch_signal);
/**
* @brief Deinitialize OTA module specified by the 'handle', and release the related resource.
* You must call this interface to release resource if reboot is not invoked after downloading.
*
* @param [in] handle: specify the OTA module.
*
* @retval 0 : Successful.
* @retval < 0 : Failed, the value is error code.
* @see None.
*/
int IOT_OTA_Deinit(void *handle);
/**
* @brief Report firmware version information to OTA server (optional).
* NOTE: please
*
* @param [in] handle: specify the OTA module.
* @param [in] version: specify the firmware version in string format.
*
* @retval 0 : Successful.
* @retval < 0 : Failed, the value is error code.
* @see None.
*/
int IOT_OTA_ReportVersion(void *handle, const char *version);
/**
* @brief Report detail progress to OTA server (optional).
* NOTE: please
*
* @param [in] handle: specify the OTA module.
* @param [in] progress: specify the progress defined by 'IOT_OTA_Progress_t'.
* @param [in] msg: detail progress information in string.
*
* @retval 0 : Successful.
* @retval < 0 : Failed, the value is error code.
* @see None.
*/
int IOT_OTA_ReportProgress(void *handle, IOT_OTA_Progress_t progress, const char *msg);
/**
* @brief Check whether is on fetching state
*
* @param [in] handle: specify the OTA module.
*
* @retval 1 : Yes.
* @retval 0 : No.
* @see None.
*/
int IOT_OTA_IsFetching(void *handle);
/**
* @brief Check whether is on end-of-fetch state.
*
* @param [in] handle: specify the OTA module.
*
* @retval 1 : Yes.
* @retval 0 : False.
* @see None.
*/
int IOT_OTA_IsFetchFinish(void *handle);
/**
* @brief fetch firmware from remote server with specific timeout value.
* NOTE: If you want to download more faster, the bigger 'buf' should be given.
*
* @param [in] handle: specify the OTA module.
* @param [out] buf: specify the space for storing firmware data.
* @param [in] buf_len: specify the length of 'buf' in bytes.
* @param [in] timeout_s: specify the timeout value in second.
*
* @retval < 0 : Error occur..
* @retval 0 : No any data be downloaded in 'timeout_s' timeout period.
* @retval (0, len] : The length of data be downloaded in 'timeout_s' timeout period in bytes.
* @see None.
*/
int IOT_OTA_FetchYield(void *handle, char *buf, uint32_t buf_len, uint32_t timeout_s);
/**
* @brief Get OTA information specified by 'type'.
* By this interface, you can get information like state, size of file, md5 of file, etc.
*
* @param [in] handle: handle of the specific OTA
* @param [in] type: specify what information you want, see detail 'IOT_OTA_CmdType_t'
* @param [out] buf: specify buffer for data exchange
* @param [in] buf_len: specify the length of 'buf' in byte.
* @return
@verbatim
NOTE:
1) When type is IOT_OTAG_FETCHED_SIZE, 'buf' should be pointer of uint32_t, and 'buf_len' should be 4.
2) When type is IOT_OTAG_FILE_SIZE, 'buf' should be pointer of uint32_t, and 'buf_len' should be 4.
3) When type is IOT_OTAG_MD5SUM, 'buf' should be a buffer, and 'buf_len' should be 33.
4) When type is IOT_OTAG_VERSION, 'buf' should be a buffer, and 'buf_len' should be OTA_VERSION_LEN_MAX.
5) When type is IOT_OTAG_CHECK_FIRMWARE, 'buf' should be pointer of uint32_t, and 'buf_len' should be 4.
0, firmware is invalid; 1, firmware is valid.
@endverbatim
*
* @retval 0 : Successful.
* @retval < 0 : Failed, the value is error code.
* @see None.
*/
int IOT_OTA_Ioctl(void *handle, IOT_OTA_CmdType_t type, void *buf, int buf_len);
/**
* @brief Get last error code.
*
* @param [in] handle: specify the OTA module.
*
* @return The error code.
* @see None.
*/
int IOT_OTA_GetLastError(void *handle);
/** @} */ /* end of api_ota */
/** @} */ /* end of api */
#if defined(__cplusplus)
}
#endif
#endif /* __OTA_EXPORT_H__ */
/*
*
*/
#include "iotx_ota_internal.h"
/* ofc, OTA fetch channel */
typedef struct {
const char *url;
httpclient_t http; /* http client */
httpclient_data_t http_data; /* http client data */
} otahttp_Struct_t, *otahttp_Struct_pt;
extern int httpclient_common(httpclient_t *client,
const char *url,
int port,
const char *ca_crt,
HTTPCLIENT_REQUEST_TYPE method,
uint32_t timeout_ms,
httpclient_data_t *client_data);
void *ofc_Init(char *url)
{
otahttp_Struct_pt h_odc;
if (NULL == (h_odc = OTA_MALLOC(sizeof(otahttp_Struct_t)))) {
OTA_LOG_ERROR("allocate for h_odc failed");
return NULL;
}
memset(h_odc, 0, sizeof(otahttp_Struct_t));
/* set http request-header parameter */
h_odc->http.header = "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
#if defined(SUPPORT_ITLS)
char *s_ptr = strstr(url, "://");
if (strlen("https") == (s_ptr - url) && (0 == strncmp(url, "https", strlen("https")))) {
strncpy(url + 1, url, strlen("http"));
url++;
}
#endif
h_odc->url = url;
return h_odc;
}
extern const char *iotx_ca_crt;
int32_t ofc_Fetch(void *handle, char *buf, uint32_t buf_len, uint32_t timeout_s)
{
int diff;
otahttp_Struct_pt h_odc = (otahttp_Struct_pt)handle;
h_odc->http_data.response_buf = buf;
h_odc->http_data.response_buf_len = buf_len;
diff = h_odc->http_data.response_content_len - h_odc->http_data.retrieve_len;
#if !defined(SUPPORT_TLS)
if (0 != httpclient_common(&h_odc->http, h_odc->url, 80, 0, HTTPCLIENT_GET, timeout_s * 1000,
&h_odc->http_data)) {
#else
if (0 != httpclient_common(&h_odc->http, h_odc->url, 443, iotx_ca_crt, HTTPCLIENT_GET, timeout_s * 1000,
&h_odc->http_data)) {
#endif
OTA_LOG_ERROR("fetch firmware failed");
return -1;
}
return h_odc->http_data.response_content_len - h_odc->http_data.retrieve_len - diff;
}
int ofc_Deinit(void *handle)
{
if (NULL != handle) {
OTA_FREE(handle);
}
return 0;
}
/*
*
*/
#include "iotx_ota_internal.h"
const char *otalib_JsonValueOf(const char *json, uint32_t json_len, const char *key, uint32_t *val_len)
{
int length;
const char *val;
val = json_get_value_by_name((char *)json, json_len, (char *)key, &length, NULL);
if (NULL != val) {
*val_len = (uint32_t) length;
}
return val;
}
void *otalib_MD5Init(void)
{
iot_md5_context *ctx = OTA_MALLOC(sizeof(iot_md5_context));
if (NULL == ctx) {
return NULL;
}
utils_md5_init(ctx);
utils_md5_starts(ctx);
return ctx;
}
void otalib_MD5Update(void *md5, const char *buf, size_t buf_len)
{
utils_md5_update(md5, (unsigned char *)buf, buf_len);
}
void otalib_MD5Finalize(void *md5, char *output_str)
{
int i;
unsigned char buf_out[16];
utils_md5_finish(md5, buf_out);
for (i = 0; i < 16; ++i) {
output_str[i * 2] = infra_hex2char(buf_out[i] >> 4);
output_str[i * 2 + 1] = infra_hex2char(buf_out[i]);
}
output_str[32] = '\0';
}
void otalib_MD5Deinit(void *md5)
{
if (NULL != md5) {
OTA_FREE(md5);
}
}
void *otalib_Sha256Init(void)
{
iot_sha256_context *ctx = OTA_MALLOC(sizeof(iot_sha256_context));
if (NULL == ctx) {
return NULL;
}
utils_sha256_init(ctx);
utils_sha256_starts(ctx);
return ctx;
}
void otalib_Sha256Update(void *sha256, const char *buf, size_t buf_len)
{
utils_sha256_update(sha256, (unsigned char *)buf, buf_len);
}
void otalib_Sha256Finalize(void *sha256, char *output_str)
{
int i;
unsigned char buf_out[32];
utils_sha256_finish(sha256, buf_out);
for (i = 0; i < 32; ++i) {
output_str[i * 2] = infra_hex2char(buf_out[i] >> 4);
output_str[i * 2 + 1] = infra_hex2char(buf_out[i]);
}
output_str[64] = '\0';
}
void otalib_Sha256Deinit(void *sha256)
{
utils_sha256_free(sha256);
if (NULL != sha256) {
OTA_FREE(sha256);
}
}
/* Get the specific @key value, and copy to @dest */
/* 0, successful; -1, failed */
int otalib_GetFirmwareFixlenPara(const char *json_doc,
size_t json_doc_len,
const char *key,
char *dest,
size_t dest_len)
{
const char *pvalue;
uint32_t val_len;
if (NULL == (pvalue = otalib_JsonValueOf(json_doc, json_doc_len, key, &val_len))) {
OTA_LOG_ERROR("Not '%s' key in json doc of OTA", key);
return -1;
}
if (val_len > dest_len) {
OTA_LOG_ERROR("value length of the key is too long");
return -1;
}
memcpy(dest, pvalue, val_len);
return 0;
}
/* Get variant length parameter of firmware, and copy to @dest */
/* 0, successful; -1, failed */
int otalib_GetFirmwareVarlenPara(const char *json_doc,
size_t json_doc_len,
const char *key,
char **dest)
{
const char *pvalue;
uint32_t val_len;
if (NULL == (pvalue = otalib_JsonValueOf(json_doc, json_doc_len, key, &val_len))) {
OTA_LOG_ERROR("Not %s key in json doc of OTA", key);
return -1;
}
if (NULL == (*dest = OTA_MALLOC(val_len + 1))) {
OTA_LOG_ERROR("allocate for dest failed");
return -1;
}
memcpy(*dest, pvalue, val_len);
(*dest)[val_len] = '\0';
return 0;
}
int otalib_GetParams(const char *json_doc, uint32_t json_len, char **url, char **version, char *md5,
uint32_t *file_size)
{
#define OTA_FILESIZE_STR_LEN (16)
char file_size_str[OTA_FILESIZE_STR_LEN + 1] = {0};
/* get version */
if (0 != otalib_GetFirmwareVarlenPara(json_doc, json_len, "version", version)) {
OTA_LOG_ERROR("get value of version key failed");
return -1;
}
/* get URL */
if (0 != otalib_GetFirmwareVarlenPara(json_doc, json_len, "url", url)) {
OTA_LOG_ERROR("get value of url key failed");
return -1;
}
/* get md5 */
if (0 != otalib_GetFirmwareFixlenPara(json_doc, json_len, "md5", md5, 32)) {
OTA_LOG_ERROR("get value of md5 key failed");
return -1;
}
/* get file size */
if (0 != otalib_GetFirmwareFixlenPara(json_doc, json_len, "size", file_size_str, OTA_FILESIZE_STR_LEN)) {
OTA_LOG_ERROR("get value of size key failed");
return -1;
}
file_size_str[OTA_FILESIZE_STR_LEN] = '\0';
*file_size = atoi(file_size_str);
return 0;
#undef OTA_FILESIZE_STR_LEN
}
int otalib_GetConfigParams(const char *json_doc, uint32_t json_len, char **configId, uint32_t *configSize, char **sign,
char **signMethod, char **url, char **getType)
{
#define OTA_FILESIZE_STR_LEN (16)
char file_size_str[OTA_FILESIZE_STR_LEN + 1];
/* get configId */
if (0 != otalib_GetFirmwareVarlenPara(json_doc, json_len, "configId", configId)) {
OTA_LOG_ERROR("get value of configId key failed");
return -1;
}
/* get configSize */
if (0 != otalib_GetFirmwareFixlenPara(json_doc, json_len, "configSize", file_size_str, OTA_FILESIZE_STR_LEN)) {
OTA_LOG_ERROR("get value of size key failed");
return -1;
}
file_size_str[OTA_FILESIZE_STR_LEN] = '\0';
*configSize = atoi(file_size_str);
/* get sign */
if (0 != otalib_GetFirmwareVarlenPara(json_doc, json_len, "sign", sign)) {
OTA_LOG_ERROR("get value of sign key failed");
return -1;
}
/* get signMethod */
if (0 != otalib_GetFirmwareVarlenPara(json_doc, json_len, "signMethod", signMethod)) {
OTA_LOG_ERROR("get value of signMethod key failed");
return -1;
}
/* get url */
if (0 != otalib_GetFirmwareVarlenPara(json_doc, json_len, "url", url)) {
OTA_LOG_ERROR("get value of url key failed");
return -1;
}
/* get getType */
if (0 != otalib_GetFirmwareVarlenPara(json_doc, json_len, "getType", getType)) {
OTA_LOG_ERROR("get value of getType key failed");
return -1;
}
return 0;
#undef OTA_FILESIZE_STR_LEN
}
/* Generate firmware information according to @id, @version */
/* and then copy to @buf. */
/* 0, successful; -1, failed */
int otalib_GenInfoMsg(char *buf, size_t buf_len, uint32_t id, const char *version)
{
int ret;
ret = HAL_Snprintf(buf,
buf_len,
"{\"id\":%d,\"params\":{\"version\":\"%s\"}}",
id,
version);
if (ret < 0) {
OTA_LOG_ERROR("HAL_Snprintf failed");
return -1;
}
return 0;
}
/* Generate report information according to @id, @msg */
/* and then copy to @buf. */
/* 0, successful; -1, failed */
int otalib_GenReportMsg(char *buf, size_t buf_len, uint32_t id, int progress, const char *msg_detail)
{
int ret;
if (NULL == msg_detail) {
ret = HAL_Snprintf(buf,
buf_len,
"{\"id\":%d,\"params\":{\"step\":\"%d\",\"desc\":\"\"}}",
id,
progress);
} else {
ret = HAL_Snprintf(buf,
buf_len,
"{\"id\":%d,\"params\":{\"step\":\"%d\",\"desc\":\"%s\"}}",
id,
progress,
msg_detail);
}
if (ret < 0) {
OTA_LOG_ERROR("HAL_Snprintf failed");
return -1;
} else if (ret >= buf_len) {
OTA_LOG_ERROR("msg is too long");
return IOT_OTAE_STR_TOO_LONG;
}
return 0;
}
#ifndef _INFRA_CONFIG_H_
#define _INFRA_CONFIG_H_
#endif
#include "infra_config.h"
#include "infra_types.h"
#include "infra_defs.h"
const char * g_infra_mqtt_domain[IOTX_MQTT_DOMAIN_NUMBER] = {
"iot-as-mqtt.cn-shanghai.aliyuncs.com", /* Shanghai */
"iot-as-mqtt.ap-southeast-1.aliyuncs.com", /* Singapore */
"iot-as-mqtt.ap-northeast-1.aliyuncs.com", /* Japan */
"iot-as-mqtt.us-west-1.aliyuncs.com", /* America */
"iot-as-mqtt.eu-central-1.aliyuncs.com", /* Germany */
NULL, /* Custom */
};
const char *g_infra_http_domain[IOTX_HTTP_DOMAIN_NUMBER] = {
"iot-auth.cn-shanghai.aliyuncs.com", /* Shanghai */
"iot-auth.ap-southeast-1.aliyuncs.com", /* Singapore */
"iot-auth.ap-northeast-1.aliyuncs.com", /* Japan */
"iot-auth.us-west-1.aliyuncs.com", /* America */
"iot-auth.eu-central-1.aliyuncs.com", /* Germany */
NULL, /* Custom */
};
This diff is collapsed.
This diff is collapsed.
/*
*
*/
#ifndef _INFRA_HTTPC_H_
#define _INFRA_HTTPC_H_
#include "infra_net.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @addtogroup HttpClient
* @{
* HttpClient API implements the client-side of HTTP/1.1. It provides base interfaces to execute an HTTP request on a given URL. It also supports HTTPS (HTTP over TLS) to provide secure communication.\n
* @section HttpClient_Usage_Chapter How to use this module
* In this release, MediaTek provides two types of APIs: high level APIs and low level APIs.\n
* - \b The \b high \b level \b APIs
* - Enables to execute a single HTTP request on a given URL.
* - Call #httpclient_get(), #httpclient_post(), #httpclient_put() or #httpclient_delete() to get, post, put or delete and HTTP request.\n
* - \b The \b low \b level \b APIs
* - Enables to execute more than one HTTP requests during a Keep-Alive connection. Keep-alive is the idea of using a single TCP connection to send and receive multiple HTTP requests/responses, as opposed to opening a new connection for every single request/response pair.
* - Step1: Call #httpclient_connect() to connect to a remote server.
* - Step2: Call #httpclient_send_request() to send an HTTP request to the server.
* - Step3: Call #httpclient_recv_response() to receive an HTTP response from the server.
* - Step4: Repeat Steps 2 and 3 to execute more requests.
* - Step5: Call #httpclient_close() to close the connection.
* - Sample code: Please refer to the example under <sdk_root>/project/mt7687_hdk/apps/http_client/http_client_keepalive folder.
*/
/** @defgroup httpclient_define Define
* @{
*/
/** @brief This macro defines the HTTP port. */
#define HTTP_PORT 80
/** @brief This macro defines the HTTPS port. */
#define HTTPS_PORT 443
/**
* @}
*/
/** @defgroup httpclient_enum Enum
* @{
*/
/** @brief This enumeration defines the HTTP request type. */
typedef enum {
HTTPCLIENT_GET,
HTTPCLIENT_POST,
HTTPCLIENT_PUT,
HTTPCLIENT_DELETE,
HTTPCLIENT_HEAD
} HTTPCLIENT_REQUEST_TYPE;
/** @defgroup httpclient_struct Struct
* @{
*/
/** @brief This structure defines the httpclient_t structure. */
typedef struct {
int remote_port; /**< HTTP or HTTPS port. */
utils_network_t net;
int response_code; /**< Response code. */
char *header; /**< Custom header. */
char *auth_user; /**< Username for basic authentication. */
char *auth_password; /**< Password for basic authentication. */
} httpclient_t;
/** @brief This structure defines the HTTP data structure. */
typedef struct {
int is_more; /**< Indicates if more data needs to be retrieved. */
int is_chunked; /**< Response data is encoded in portions/chunks.*/
int retrieve_len; /**< Content length to be retrieved. */
int response_content_len; /**< Response content length. */
int response_received_len; /**< Response have received length. */
int post_buf_len; /**< Post data length. */
int response_buf_len; /**< Response buffer length. */
char *post_content_type; /**< Content type of the post data. */
char *post_buf; /**< User data to be posted. */
char *response_buf; /**< Buffer to store the response data. */
} httpclient_data_t;
int iotx_post(httpclient_t *client,
const char *url,
int port,
const char *ca_crt,
httpclient_data_t *client_data);
int httpclient_recv_response(httpclient_t *client, uint32_t timeout_ms, httpclient_data_t *client_data);
int httpclient_common(httpclient_t *client, const char *url, int port, const char *ca_crt,
HTTPCLIENT_REQUEST_TYPE method, uint32_t timeout_ms, httpclient_data_t *client_data);
void httpclient_close(httpclient_t *client);
#ifdef __cplusplus
}
#endif
#endif /* __HTTPCLIENT_H__ */
This diff is collapsed.
/*
*
*/
#ifndef _INFRA_JSON_PARSER_H_
#define _INFRA_JSON_PARSER_H_
/* #include "iotx_utils_internal.h" */
typedef struct JSON_NV {
int nLen;
int vLen;
int vType;
char *pN;
char *pV;
} JSON_NV;
/**
The descriptions of the json value node type
**/
enum JSONTYPE {
JNONE = -1,
JSTRING = 0,
JOBJECT,
JARRAY,
JNUMBER,
JBOOLEAN,
JTYPEMAX
};
/**
The error codes produced by the JSON parsers
**/
enum JSON_PARSE_CODE {
JSON_PARSE_ERR,
JSON_PARSE_OK,
JSON_PARSE_FINISH
};
/**
The return codes produced by the JSON parsers
**/
enum JSON_PARSE_RESULT {
JSON_RESULT_ERR = -1,
JSON_RESULT_OK
};
typedef int (*json_parse_cb)(char *p_cName, int iNameLen, char *p_cValue, int iValueLen, int iValueType,
void *p_Result);
/**
* @brief Parse the JSON string, and iterate through all keys and values,
* then handle the keys and values by callback function.
*
* @param[in] p_cJsonStr @n The JSON string
* @param[in] iStrLen @n The JSON string length
* @param[in] pfnCB @n Callback function
* @param[out] p_CBData @n User data
* @return JSON_RESULT_OK success, JSON_RESULT_ERR failed
* @see None.
* @note None.
**/
int json_parse_name_value(char *p_cJsonStr, int iStrLen, json_parse_cb pfnCB, void *p_CBData);
/**
* @brief Get the value by a specified key from a json string
*
* @param[in] p_cJsonStr @n the JSON string
* @param[in] iStrLen @n the JSON string length
* @param[in] p_cName @n the specified key string
* @param[out] p_iValueLen @n the value length
* @param[out] p_iValueType @n the value type
* @return A pointer to the value
* @see None.
* @note None.
**/
char *json_get_value_by_name(char *p_cJsonStr, int iStrLen, char *p_cName, int *p_iValueLen, int *p_iValueType);
/**
* @brief Get the value by a specified key from a json string
*
* @param[in] p_cJsonStr @n the JSON string
* @param[in] iStrLen @n the JSON string length
* @param[in] p_cName @n the specified key string
* @param[in] p_cNameLen @n the specified key string length
* @param[out] p_iValueLen @n the value length
* @param[out] p_iValueType @n the value type
* @return A pointer to the value
* @see None.
* @note None.
**/
char *json_get_value_by_name_len(char *p_cJsonStr, int iStrLen, char *p_cName, int p_cNameLen, int *p_iValueLen,
int *p_iValueType);
/**
* @brief Get the JSON object point associate with a given type.
*
* @param[in] type @n The object type
* @param[in] str @n The JSON string
* @param[in] str_end @n The end point of Json string
* @returns The json object point with the given field type.
* @see None.
* @note None.
*/
char *json_get_object(int type, char *str, char *str_end);
char *json_get_next_object(int type, char *str, char *str_end, char **key, int *key_len, char **val, int *val_len,
int *val_type);
/**
* @brief retrieve each key&value pair from the json string
*
* @param[in] str @n Json string to revolve
* @param[in] slen @n The length of json string
* @param[in] pos @n cursor
* @param[out] key @n pointer to the next Key object
* @param[out] klen @n Key object length
* @param[out] val @n pointer to the next Value object
* @param[out] vlen @n Value object length
* @param[out] vtype @n Value object type(digital, string, object, array)
* @see None.
* @note None.
*/
#define json_object_for_each_kv(str, slen, pos, key, klen, val, vlen, vtype) \
for (pos = json_get_object(JOBJECT, str, str + slen); \
pos != NULL && *pos!= 0 && (pos=json_get_next_object(JOBJECT, pos, str + slen , &key, &klen, &val, &vlen, &vtype))!=0; )
/**
* @brief retrieve each entry from the json array
*
* @param[in] str @n Json array to revolve
* @param[in] slen @n the length of Json array
* @param[in] pos @n cursor
* @param[out] entry @n pointer to the next entry from the array
* @param[out] len @n entry length
* @param[out] type @n entry type(digital, string, object, array)
* @see None.
* @note None.
*/
#define json_array_for_each_entry(str, slen, pos, entry, len, type) \
for (pos = json_get_object(JARRAY, str, str + slen); \
pos != NULL && *pos!= 0 && (pos=json_get_next_object(JARRAY, ++pos, str + slen, 0, 0, &entry, &len, &type))!=0; )
/**
* @brief backup the last character to register parameters,
* and set the end character with '\0'
*
* @param[in] json_str @n json string
* @param[in] str_len @n json string lenth
* @param[out] register @n used to backup the last character
* @see None.
* @note None.
*/
#define backup_json_str_last_char(json_str, str_len, register) { \
register = *((char *)json_str + str_len); \
*((char *)json_str + str_len) = '\0'; \
}
/**
* @brief restore the last character from register parameters
*
* @param[in] json_str @n json string
* @param[in] str_len @n json string lenth
* @param[in] register @n used to restore the last character
* @see None.
* @note None.
*/
#define restore_json_str_last_char(json_str, str_len, register) { \
*((char *)json_str + str_len) = register; \
}
char *LITE_json_value_of(char *key, char *src, ...);
#endif /* __JSON_PARSER_H__ */
This diff is collapsed.
/*
*
*/
#ifndef _INFRA_MD5_H_
#define _INFRA_MD5_H_
#include "infra_types.h"
typedef struct {
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[4]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
} iot_md5_context;
/**
* \brief Initialize MD5 context
*
* \param ctx MD5 context to be initialized
*/
void utils_md5_init(iot_md5_context *ctx);
/**
* \brief Clear MD5 context
*
* \param ctx MD5 context to be cleared
*/
void utils_md5_free(iot_md5_context *ctx);
/**
* \brief Clone (the state of) an MD5 context
*
* \param dst The destination context
* \param src The context to be cloned
*/
void utils_md5_clone(iot_md5_context *dst,
const iot_md5_context *src);
/**
* \brief MD5 context setup
*
* \param ctx context to be initialized
*/
void utils_md5_starts(iot_md5_context *ctx);
/**
* \brief MD5 process buffer
*
* \param ctx MD5 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void utils_md5_update(iot_md5_context *ctx, const unsigned char *input, uint32_t ilen);
/**
* \brief MD5 final digest
*
* \param ctx MD5 context
* \param output MD5 checksum result
*/
void utils_md5_finish(iot_md5_context *ctx, unsigned char output[16]);
/* Internal use */
void utils_md5_process(iot_md5_context *ctx, const unsigned char data[64]);
/**
* \brief Output = MD5( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output MD5 checksum result
*/
void utils_md5(const unsigned char *input, uint32_t ilen, unsigned char output[16]);
void utils_hmac_md5(const char *msg, int msg_len, char *digest, const char *key, int key_len);
#endif
This diff is collapsed.
/*
*
*/
#ifndef _INFRA_NET_H_
#define _INFRA_NET_H_
#include "infra_types.h"
/**
* @brief The structure of network connection(TCP or SSL).
* The user has to allocate memory for this structure.
*/
struct utils_network;
typedef struct utils_network utils_network_t, *utils_network_pt;
struct utils_network {
const char *pHostAddress;
uint16_t port;
uint16_t ca_crt_len;
/**< NULL, TCP connection; NOT NULL, SSL connection */
const char *ca_crt;
/**< NOT NULL,iTLS connection*/
char *product_key;
/**< connection handle: 0, NOT connection; NOT 0, handle of the connection */
uintptr_t handle;
/**< Read data from server function pointer. */
int (*read)(utils_network_pt, char *, uint32_t, uint32_t);
/**< Send data to server function pointer. */
int (*write)(utils_network_pt, const char *, uint32_t, uint32_t);
/**< Disconnect the network */
int (*disconnect)(utils_network_pt);
/**< Establish the network */
int (*connect)(utils_network_pt);
};
int utils_net_read(utils_network_pt pNetwork, char *buffer, uint32_t len, uint32_t timeout_ms);
int utils_net_write(utils_network_pt pNetwork, const char *buffer, uint32_t len, uint32_t timeout_ms);
int iotx_net_disconnect(utils_network_pt pNetwork);
int iotx_net_connect(utils_network_pt pNetwork);
int iotx_net_init(utils_network_pt pNetwork, const char *host, uint16_t port, const char *ca_crt);
#endif /* IOTX_COMMON_NET_H */
This diff is collapsed.
/*
*
*/
#ifndef _IOTX_COMMON_SHA256_H_
#define _IOTX_COMMON_SHA256_H_
#include <stdint.h>
#define SHA256_DIGEST_LENGTH (32)
#define SHA256_BLOCK_LENGTH (64)
#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8)
#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1)
/**
* \brief SHA-256 context structure
*/
typedef struct {
uint32_t total[2]; /*!< number of bytes processed */
uint32_t state[8]; /*!< intermediate digest state */
unsigned char buffer[64]; /*!< data block being processed */
int is224; /*!< 0 => SHA-256, else SHA-224 */
} iot_sha256_context;
typedef union {
char sptr[8];
uint64_t lint;
} u_retLen;
/**
* \brief Initialize SHA-256 context
*
* \param ctx SHA-256 context to be initialized
*/
void utils_sha256_init(iot_sha256_context *ctx);
/**
* \brief Clear SHA-256 context
*
* \param ctx SHA-256 context to be cleared
*/
void utils_sha256_free(iot_sha256_context *ctx);
/**
* \brief SHA-256 context setup
*
* \param ctx context to be initialized
*/
void utils_sha256_starts(iot_sha256_context *ctx);
/**
* \brief SHA-256 process buffer
*
* \param ctx SHA-256 context
* \param input buffer holding the data
* \param ilen length of the input data
*/
void utils_sha256_update(iot_sha256_context *ctx, const unsigned char *input, uint32_t ilen);
/**
* \brief SHA-256 final digest
*
* \param ctx SHA-256 context
* \param output SHA-256 checksum result
*/
void utils_sha256_finish(iot_sha256_context *ctx, uint8_t output[32]);
/* Internal use */
void utils_sha256_process(iot_sha256_context *ctx, const unsigned char data[64]);
/**
* \brief Output = SHA-256( input buffer )
*
* \param input buffer holding the data
* \param ilen length of the input data
* \param output SHA-256 checksum result
*/
void utils_sha256(const uint8_t *input, uint32_t ilen, uint8_t output[32]);
void utils_hmac_sha256(const uint8_t *msg, uint32_t msg_len, const uint8_t *key, uint32_t key_len, uint8_t output[32]);
#endif
This diff is collapsed.
#ifndef _INFRA_STRING_H_
#define _INFRA_STRING_H_
#include "infra_types.h"
int8_t infra_hex2char(uint8_t hex);
void infra_hex2str(uint8_t *input, uint16_t input_len, char *output);
void infra_int2str(uint32_t input, char output[10]);
char *infra_strtok(char *str, const char *delim);
int infra_randstr(char *random, int length);
void LITE_hexstr_convert(char *input, int input_len, unsigned char *output, int output_len);
int infra_str2int(const char *input, int *val);
void LITE_hexbuf_convert(unsigned char *digest, char *out, int in_len, int uppercase);
#endif
This diff is collapsed.
/*
*
*/
#ifndef _INFRA_TIMER_H_
#define _INFRA_TIMER_H_
#include "infra_types.h"
typedef struct {
uint32_t time;
} iotx_time_t;
void iotx_time_start(iotx_time_t *timer);
uint32_t utils_time_spend(iotx_time_t *start);
uint32_t iotx_time_left(iotx_time_t *end);
uint32_t utils_time_is_expired(iotx_time_t *timer);
void iotx_time_init(iotx_time_t *timer);
void utils_time_countdown_ms(iotx_time_t *timer, uint32_t millisecond);
uint32_t utils_time_get_ms(void);
#endif /* _IOTX_COMMON_TIMER_H_ */
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment