support aliyun sdk on TencentOS tiny

sample: examples\aliyun_iotkit_csdk_mqtt
project: board\TencentOS_tiny_EVB_MX_Plus\KEIL\aliyun_iotkit_csdk_mqtt
This commit is contained in:
dcxajichu
2019-10-31 16:36:28 +08:00
parent 30ea36a7ab
commit 8c24d921b0
692 changed files with 199829 additions and 0 deletions

View File

@@ -0,0 +1,239 @@
#ifdef DEV_BIND_ENABLED
#include "infra_config.h"
#include <string.h>
#include "infra_defs.h"
#include "dev_bind_wrapper.h"
#endif
#if defined(WIFI_PROVISION_ENABLED)
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "iot_import_awss.h"
/**
* @brief 获取配网服务(`AWSS`)的超时时间长度, 单位是毫秒
*
* @return 超时时长, 单位是毫秒
* @note 推荐时长是60,0000毫秒
*/
int HAL_Awss_Get_Timeout_Interval_Ms(void)
{
return 30 * 60 * 1000;
}
/**
* @brief 获取在每个信道(`channel`)上扫描的时间长度, 单位是毫秒
*
* @return 时间长度, 单位是毫秒
* @note 推荐时长是200毫秒到400毫秒
*/
int HAL_Awss_Get_Channelscan_Interval_Ms(void)
{
return 250;
}
/**
* @brief 设置Wi-Fi网卡工作在监听(Monitor)模式, 并在收到802.11帧的时候调用被传入的回调函数
*
* @param[in] cb @n A function pointer, called back when wifi receive a frame.
*/
void HAL_Awss_Open_Monitor(_IN_ awss_recv_80211_frame_cb_t cb)
{
}
/**
* @brief 设置Wi-Fi网卡离开监听(Monitor)模式, 并开始以站点(Station)模式工作
*/
void HAL_Awss_Close_Monitor(void)
{
}
/**
* @brief 设置Wi-Fi网卡切换到指定的信道(channel)上
*
* @param[in] primary_channel @n Primary channel.
* @param[in] secondary_channel @n Auxiliary channel if 40Mhz channel is supported, currently
* this param is always 0.
* @param[in] bssid @n A pointer to wifi BSSID on which awss lock the channel, most HAL
* may ignore it.
*/
void HAL_Awss_Switch_Channel(
_IN_ char primary_channel,
_IN_OPT_ char secondary_channel,
_IN_OPT_ uint8_t bssid[ETH_ALEN])
{
}
/**
* @brief 要求Wi-Fi网卡连接指定热点(Access Point)的函数
*
* @param[in] connection_timeout_ms @n AP connection timeout in ms or HAL_WAIT_INFINITE
* @param[in] ssid @n AP ssid
* @param[in] passwd @n AP passwd
* @param[in] auth @n optional(AWSS_AUTH_TYPE_INVALID), AP auth info
* @param[in] encry @n optional(AWSS_ENC_TYPE_INVALID), AP encry info
* @param[in] bssid @n optional(NULL or zero mac address), AP bssid info
* @param[in] channel @n optional, AP channel info
* @return
@verbatim
= 0: connect AP & DHCP success
= -1: connect AP or DHCP fail/timeout
@endverbatim
* @see None.
* @note
* If the STA connects the old AP, HAL should disconnect from the old AP firstly.
* If bssid specifies the dest AP, HAL should use bssid to connect dest AP.
*/
int HAL_Awss_Connect_Ap(
_IN_ uint32_t connection_timeout_ms,
_IN_ char ssid[HAL_MAX_SSID_LEN],
_IN_ char passwd[HAL_MAX_PASSWD_LEN],
_IN_OPT_ enum AWSS_AUTH_TYPE auth,
_IN_OPT_ enum AWSS_ENC_TYPE encry,
_IN_OPT_ uint8_t bssid[ETH_ALEN],
_IN_OPT_ uint8_t channel)
{
return 0;
}
/**
* @brief check system network is ready(get ip address) or not.
*
* @param None.
* @return 0, net is not ready; 1, net is ready.
* @see None.
* @note None.
*/
int HAL_Sys_Net_Is_Ready()
{
return 0;
}
/**
* @brief 在当前信道(channel)上以基本数据速率(1Mbps)发送裸的802.11帧(raw 802.11 frame)
*
* @param[in] type @n see enum HAL_Awss_frame_type, currently only FRAME_BEACON
* FRAME_PROBE_REQ is used
* @param[in] buffer @n 80211 raw frame, include complete mac header & FCS field
* @param[in] len @n 80211 raw frame length
* @return
@verbatim
= 0, send success.
= -1, send failure.
= -2, unsupported.
@endverbatim
* @see None.
* @note awss use this API send raw frame in wifi monitor mode & station mode
*/
int HAL_Wifi_Send_80211_Raw_Frame(_IN_ enum HAL_Awss_Frame_Type type,
_IN_ uint8_t *buffer, _IN_ int len)
{
return 0;
}
/**
* @brief 在站点(Station)模式下使能或禁用对管理帧的过滤
*
* @param[in] filter_mask @n see mask macro in enum HAL_Awss_frame_type,
* currently only FRAME_PROBE_REQ_MASK & FRAME_BEACON_MASK is used
* @param[in] vendor_oui @n oui can be used for precise frame match, optional
* @param[in] callback @n see awss_wifi_mgmt_frame_cb_t, passing 80211
* frame or ie to callback. when callback is NULL
* disable sniffer feature, otherwise enable it.
* @return
@verbatim
= 0, success
= -1, fail
= -2, unsupported.
@endverbatim
* @see None.
* @note awss use this API to filter specific mgnt frame in wifi station mode
*/
int HAL_Wifi_Enable_Mgmt_Frame_Filter(
_IN_ uint32_t filter_mask,
_IN_OPT_ uint8_t vendor_oui[3],
_IN_ awss_wifi_mgmt_frame_cb_t callback)
{
return 0;
}
/**
* @brief 启动一次Wi-Fi的空中扫描(Scan)
*
* @param[in] cb @n pass ssid info(scan result) to this callback one by one
* @return 0 for wifi scan is done, otherwise return -1
* @see None.
* @note
* This API should NOT exit before the invoking for cb is finished.
* This rule is something like the following :
* HAL_Wifi_Scan() is invoked...
* ...
* for (ap = first_ap; ap <= last_ap; ap = next_ap){
* cb(ap)
* }
* ...
* HAL_Wifi_Scan() exit...
*/
int HAL_Wifi_Scan(awss_wifi_scan_result_cb_t cb)
{
return 0;
}
/**
* @brief 获取所连接的热点(Access Point)的信息
*
* @param[out] ssid: array to store ap ssid. It will be null if ssid is not required.
* @param[out] passwd: array to store ap password. It will be null if ap password is not required.
* @param[out] bssid: array to store ap bssid. It will be null if bssid is not required.
* @return
@verbatim
= 0: succeeded
= -1: failed
@endverbatim
* @see None.
* @note
* If the STA dosen't connect AP successfully, HAL should return -1 and not touch the ssid/passwd/bssid buffer.
*/
int HAL_Wifi_Get_Ap_Info(
_OU_ char ssid[HAL_MAX_SSID_LEN],
_OU_ char passwd[HAL_MAX_PASSWD_LEN],
_OU_ uint8_t bssid[ETH_ALEN])
{
return 0;
}
/* @brief 打开当前设备热点并把设备由SoftAP模式切换到AP模式
*/
int HAL_Awss_Open_Ap(const char *ssid, const char *passwd, int beacon_interval, int hide)
{
return 0;
}
/* @brief 关闭当前设备热点并把设备由SoftAP模式切换到Station模式
*/
int HAL_Awss_Close_Ap()
{
return 0;
}
#endif /* #if defined(HAL_AWSS) */
#ifdef DEV_BIND_ENABLED
/**
* @brief 获取Wi-Fi网口的MAC地址, 格式应当是"XX:XX:XX:XX:XX:XX"
*
* @param mac_str : 用于存放MAC地址字符串的缓冲区数组
* @return 指向缓冲区数组起始位置的字符指针
*/
char *HAL_Wifi_Get_Mac(_OU_ char mac_str[HAL_MAC_LEN])
{
strcpy(mac_str, "18:FE:34:12:33:44");
return mac_str;
}
#endif

View File

@@ -0,0 +1,149 @@
#include "infra_config.h"
#if defined(HAL_CRYPTO)
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <string.h>
#include <stdlib.h>
#include "infra_compat.h"
#include "mbedtls/aes.h"
#define AES_BLOCK_SIZE 16
typedef struct {
mbedtls_aes_context ctx;
uint8_t iv[16];
uint8_t key[16];
} platform_aes_t;
p_HAL_Aes128_t HAL_Aes128_Init(
const uint8_t *key,
const uint8_t *iv,
AES_DIR_t dir)
{
int ret = 0;
platform_aes_t *p_aes128 = NULL;
if (!key || !iv) return p_aes128;
p_aes128 = (platform_aes_t *)calloc(1, sizeof(platform_aes_t));
if (!p_aes128) return p_aes128;
mbedtls_aes_init(&p_aes128->ctx);
if (dir == HAL_AES_ENCRYPTION) {
ret = mbedtls_aes_setkey_enc(&p_aes128->ctx, key, 128);
} else {
ret = mbedtls_aes_setkey_dec(&p_aes128->ctx, key, 128);
}
if (ret == 0) {
memcpy(p_aes128->iv, iv, 16);
memcpy(p_aes128->key, key, 16);
} else {
free(p_aes128);
p_aes128 = NULL;
}
return (p_HAL_Aes128_t *)p_aes128;
}
int HAL_Aes128_Destroy(p_HAL_Aes128_t aes)
{
if (!aes) return -1;
mbedtls_aes_free(&((platform_aes_t *)aes)->ctx);
free(aes);
return 0;
}
int HAL_Aes128_Cbc_Encrypt(
p_HAL_Aes128_t aes,
const void *src,
size_t blockNum,
void *dst)
{
int i = 0;
int ret = ret;
platform_aes_t *p_aes128 = (platform_aes_t *)aes;
if (!aes || !src || !dst) return -1;
for (i = 0; i < blockNum; ++i) {
ret = mbedtls_aes_crypt_cbc(&p_aes128->ctx, MBEDTLS_AES_ENCRYPT, AES_BLOCK_SIZE,
p_aes128->iv, src, dst);
src += 16;
dst += 16;
}
return ret;
}
int HAL_Aes128_Cbc_Decrypt(
p_HAL_Aes128_t aes,
const void *src,
size_t blockNum,
void *dst)
{
int i = 0;
int ret = -1;
platform_aes_t *p_aes128 = (platform_aes_t *)aes;
if (!aes || !src || !dst) return ret;
for (i = 0; i < blockNum; ++i) {
ret = mbedtls_aes_crypt_cbc(&p_aes128->ctx, MBEDTLS_AES_DECRYPT, AES_BLOCK_SIZE,
p_aes128->iv, src, dst);
src += 16;
dst += 16;
}
return ret;
}
#if defined(MBEDTLS_CIPHER_MODE_CFB)
int HAL_Aes128_Cfb_Encrypt(
p_HAL_Aes128_t aes,
const void *src,
size_t length,
void *dst)
{
size_t offset = 0;
int ret = -1;
platform_aes_t *p_aes128 = (platform_aes_t *)aes;
if (!aes || !src || !dst) return ret;
ret = mbedtls_aes_crypt_cfb128(&p_aes128->ctx, MBEDTLS_AES_ENCRYPT, length,
&offset, p_aes128->iv, src, dst);
return ret;
}
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
int HAL_Aes128_Cfb_Decrypt(
p_HAL_Aes128_t aes,
const void *src,
size_t length,
void *dst)
{
size_t offset = 0;
int ret = -1;
platform_aes_t *p_aes128 = (platform_aes_t *)aes;
if (!aes || !src || !dst) return ret;
ret = mbedtls_aes_setkey_enc(&p_aes128->ctx, p_aes128->key, 128);
ret = mbedtls_aes_crypt_cfb128(&p_aes128->ctx, MBEDTLS_AES_DECRYPT, length,
&offset, p_aes128->iv, src, dst);
return ret;
}
#endif
#endif /* #if defined(HAL_CRYPTO) */

View File

@@ -0,0 +1,41 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include "infra_config.h"
#ifdef FS_ENABLED
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
void *HAL_Fopen(const char *path, const char *mode)
{
return (void *)fopen(path, mode);
}
uint32_t HAL_Fread(void *buff, uint32_t size, uint32_t count, void *stream)
{
return fread(buff, (size_t)size, (size_t)count, (FILE *)stream);
}
uint32_t HAL_Fwrite(const void *ptr, uint32_t size, uint32_t count, void *stream)
{
return (uint32_t)fwrite(ptr, (size_t)size, (size_t)count, (FILE *)stream);
}
int HAL_Fseek(void *stream, long offset, int framewhere)
{
return fseek((FILE *)stream, offset, framewhere);
}
int HAL_Fclose(void *stream)
{
return fclose((FILE *)stream);
}
long HAL_Ftell(void *stream)
{
return ftell((FILE *)stream);
}
#endif

View File

@@ -0,0 +1,471 @@
#include "infra_config.h"
#if defined(HAL_KV)
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "stdint.h"
#include <fcntl.h>
#include <pthread.h>
#include <sys/stat.h>
#include <unistd.h>
#include "infra_defs.h"
#define TABLE_COL_SIZE (384)
#define TABLE_ROW_SIZE (2)
#define ITEM_MAX_KEY_LEN 128 /* The max key length for key-value item */
#define ITEM_MAX_VAL_LEN 512 /* The max value length for key-value item */
#define ITEM_MAX_LEN sizeof(kv_item_t)
#define KV_FILE_NAME "linkkit_kv.bin"
#define kv_err(...) do{printf(__VA_ARGS__);printf("\r\n");}while(0)
typedef struct kv {
char key[ITEM_MAX_KEY_LEN];
uint8_t value[ITEM_MAX_VAL_LEN];
int value_len;
} kv_item_t;
typedef struct kv_file_s {
const char *filename;
pthread_mutex_t lock;
} kv_file_t;
static int kv_get(const char *key, void *value, int *value_len);
static int kv_set(const char *key, void *value, int value_len);
static int kv_del(const char *key);
static unsigned int hash_gen(const char *key);
static int hash_table_put(kv_file_t *file, const char *key, void *value, int value_len);
static int hash_table_get(kv_file_t *file, const char *key, void *value, int *len);
static int hash_table_rm(kv_file_t *file, const char *key);
static kv_file_t *kv_open(const char *filename);
static int read_kv_item(const char *filename, void *buf, int location);
static int write_kv_item(const char *filename, void *data, int location);
static void free_kv(struct kv *kv)
{
if (kv) {
kv->value_len = 0;
free(kv);
}
}
static unsigned int hash_gen(const char *key)
{
unsigned int hash = 0;
while (*key) {
hash = (hash << 5) + hash + *key++;
}
return hash % TABLE_COL_SIZE;
}
/* insert or update a value indexed by key */
static int hash_table_put(kv_file_t *file, const char *key, void *value, int value_len)
{
int i;
int read_size;
kv_item_t *kv;
int j = 0;
kv_item_t *p;
if (!file || !file->filename || !key || !value || value_len <= 0) {
kv_err("paras err");
return -1;
}
value_len = value_len > ITEM_MAX_VAL_LEN ? ITEM_MAX_VAL_LEN : value_len;
i = hash_gen(key);
kv_err("hash i= %d", i);
read_size = ITEM_MAX_LEN * TABLE_ROW_SIZE;
kv = malloc(read_size);
if (kv == NULL) {
kv_err("malloc kv err");
return -1;
}
memset(kv, 0, read_size);
if (read_kv_item(file->filename, kv, i) != 0) {
kv_err("read kv err");
free_kv(kv);
return -1;
}
p = &kv[j];
while (p && p->value_len) { /* if key is already stroed, update its value */
if (strcmp(p->key, key) == 0) {
memset(p->value, 0, ITEM_MAX_VAL_LEN);
memcpy(p->value, value, value_len);
p->value_len = value_len;
break;
}
if (++j == TABLE_ROW_SIZE) {
kv_err("hash row full");
free(kv);
return -1;
}
p = &kv[j];
}
p = &kv[j];
if (p && !p->value_len) {/* if key has not been stored, then add it */
//p->next = NULL;
strncpy(p->key, key, ITEM_MAX_KEY_LEN - 1);
memcpy(p->value, value, value_len);
p->value_len = value_len;
}
if (write_kv_item(file->filename, kv, i) < 0) {
kv_err("write_kv_item err");
free(kv);
return -1;
}
free(kv);
return 0;
}
/* get a value indexed by key */
static int hash_table_get(kv_file_t *file, const char *key, void *value, int *len)
{
int i;
int read_size;
kv_item_t *kv;
int j = 0;
struct kv *p;
if (!file || !file->filename || !key || !value || !len || *len <= 0) {
kv_err("paras err");
return -1;
}
i = hash_gen(key);
read_size = sizeof(kv_item_t) * TABLE_ROW_SIZE;
kv = malloc(read_size);
if (kv == NULL) {
kv_err("malloc kv err");
return -1;
}
memset(kv, 0, read_size);
if (read_kv_item(file->filename, kv, i) != 0) {
kv_err("read kv err");
free_kv(kv);
return -1;
}
// struct kv *p = ht->table[i];
p = &kv[j];
while (p && p->value_len) {
if (strcmp(key, p->key) == 0) {
*len = p->value_len < *len ? p->value_len : *len;
memcpy(value, p->value, *len);
free_kv(kv);
return 0;
}
if (++j == TABLE_ROW_SIZE) {
break;
}
p = &kv[j];
}
free_kv(kv);
kv_err("not found");
return -1;
}
/* remove a value indexed by key */
static int hash_table_rm(kv_file_t *file, const char *key)
{
int i;
int read_size;
kv_item_t *kv;
int j = 0;
struct kv *p;
if (!file || !file->filename || !key) {
return -1;
}
i = hash_gen(key) % TABLE_COL_SIZE;
read_size = sizeof(kv_item_t) * TABLE_ROW_SIZE;
kv = malloc(read_size);
if (kv == NULL) {
return -1;
}
memset(kv, 0, read_size);
if (read_kv_item(file->filename, kv, i) != 0) {
free_kv(kv);
return -1;
}
p = &kv[j];
while (p && p->value_len) {
if (strcmp(key, p->key) == 0) {
memset(p, 0, ITEM_MAX_LEN);
}
if (++j == TABLE_ROW_SIZE) {
break;
}
p = &kv[j];
}
if (write_kv_item(file->filename, kv, i) < 0) {
free_kv(kv);
return -1;
}
free_kv(kv);
return 0;
}
static int read_kv_item(const char *filename, void *buf, int location)
{
struct stat st;
int ret = 0;
int offset;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
kv_err("open err");
return -1;
}
if (fstat(fd, &st) < 0) {
kv_err("fstat err");
close(fd);
return -1;
}
if (st.st_size < (location + 1) *ITEM_MAX_LEN * TABLE_ROW_SIZE) {
kv_err("read overstep");
close(fd);
return -1;
}
offset = location * ITEM_MAX_LEN * TABLE_ROW_SIZE;
ret = lseek(fd, offset, SEEK_SET);
if (ret < 0) {
kv_err("lseek err");
close(fd);
return -1;
}
if (read(fd, buf, ITEM_MAX_LEN * TABLE_ROW_SIZE) != ITEM_MAX_LEN * TABLE_ROW_SIZE) {
kv_err("read err");
close(fd);
return -1;
}
close(fd);
return 0;
}
static int write_kv_item(const char *filename, void *data, int location)
{
struct stat st;
int offset;
int ret;
int fd = open(filename, O_WRONLY);
if (fd < 0) {
return -1;
}
if (fstat(fd, &st) < 0) {
kv_err("fstat err");
close(fd);
return -1;
}
if (st.st_size < (location + 1) *ITEM_MAX_LEN * TABLE_ROW_SIZE) {
kv_err("overstep st.st_size = %d location =%d cur loc=%d",
(int)st.st_size,
(int)location,
(int)((location + 1) *ITEM_MAX_LEN * TABLE_ROW_SIZE));
close(fd);
return -1;
}
offset = (location) * ITEM_MAX_LEN * TABLE_ROW_SIZE;
ret = lseek(fd, offset, SEEK_SET);
if (ret < 0) {
kv_err("lseek err");
close(fd);
return -1;
}
if (write(fd, data, ITEM_MAX_LEN * TABLE_ROW_SIZE) != ITEM_MAX_LEN * TABLE_ROW_SIZE) {
kv_err("kv write failed");
close(fd);
return -1;
}
fsync(fd);
close(fd);
return 0;
}
static int create_hash_file(kv_file_t *hash_kv)
{
int i;
int fd;
char init_data[ITEM_MAX_LEN * TABLE_ROW_SIZE] = {0};
if (hash_kv == NULL) {
return -1;
}
fd = open(hash_kv->filename, O_CREAT | O_RDWR, 0644);
if (fd < 0) {
return -1;
}
for (i = 0; i < TABLE_COL_SIZE ; i++) {
if (write(fd, init_data, ITEM_MAX_LEN * TABLE_ROW_SIZE) != ITEM_MAX_LEN *
TABLE_ROW_SIZE) { /* 3 = '{}' + null terminator */
kv_err("write err");
close(fd);
return -1;
}
}
if (fsync(fd) < 0) {
close(fd);
return -1;
}
close(fd);
return 0;
}
static kv_file_t *kv_open(const char *filename)
{
kv_file_t *file = malloc(sizeof(kv_file_t));
if (!file) {
return NULL;
}
memset(file, 0, sizeof(kv_file_t));
file->filename = filename;
pthread_mutex_init(&file->lock, NULL);
pthread_mutex_lock(&file->lock);
if (access(file->filename, F_OK) < 0) {
/* create KV file when not exist */
if (create_hash_file(file) < 0) {
goto fail;
}
}
pthread_mutex_unlock(&file->lock);
return file;
fail:
pthread_mutex_unlock(&file->lock);
free(file);
return NULL;
}
static int __kv_get(kv_file_t *file, const char *key, void *value, int *value_len)
{
int ret;
if (!file || !key || !value || !value_len || *value_len <= 0) {
return -1;
}
pthread_mutex_lock(&file->lock);
ret = hash_table_get(file, key, value, value_len);
pthread_mutex_unlock(&file->lock);
return ret;
}
static int __kv_set(kv_file_t *file, const char *key, void *value, int value_len)
{
int ret;
if (!file || !key || !value || value_len <= 0) {
return -1;
}
pthread_mutex_lock(&file->lock);
ret = hash_table_put(file, key, value, value_len);
pthread_mutex_unlock(&file->lock);
return ret;
}
int __kv_del(kv_file_t *file, const char *key)
{
int ret;
if (!file || !key) {
return -1;
}
/* remove old value if exist */
pthread_mutex_lock(&file->lock);
ret = hash_table_rm(file, key);
pthread_mutex_unlock(&file->lock);
return ret;
}
static kv_file_t *file = NULL;
static int kv_get(const char *key, void *value, int *value_len)
{
if (!file) {
file = kv_open(KV_FILE_NAME);
if (!file) {
kv_err("kv_open failed");
return -1;
}
}
return __kv_get(file, key, value, value_len);
}
static int kv_set(const char *key, void *value, int value_len)
{
if (!file) {
file = kv_open(KV_FILE_NAME);
if (!file) {
kv_err("kv_open failed");
return -1;
}
}
return __kv_set(file, key, value, value_len);
}
static int kv_del(const char *key)
{
if (!file) {
file = kv_open(KV_FILE_NAME);
if (!file) {
kv_err("kv_open failed");
return -1;
}
}
return __kv_del(file, key);
}
int HAL_Kv_Set(const char *key, const void *val, int len, int sync)
{
return kv_set(key, (void *)val, len);
}
int HAL_Kv_Get(const char *key, void *val, int *buffer_len)
{
return kv_get(key, val, buffer_len);
}
int HAL_Kv_Del(const char *key)
{
return kv_del(key);
}
#endif /* #if defined(HAL_KV) */

View File

@@ -0,0 +1,624 @@
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <memory.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <sys/time.h>
#include <semaphore.h>
#include <errno.h>
#include <assert.h>
#include <net/if.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <sys/reboot.h>
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include "infra_config.h"
#include "infra_compat.h"
#include "infra_defs.h"
#include "wrappers_defs.h"
#define PLATFORM_WAIT_INFINITE (~0)
#ifdef DYNAMIC_REGISTER
char _product_key[IOTX_PRODUCT_KEY_LEN + 1] = "a1ZETBPbycq";
char _product_secret[IOTX_PRODUCT_SECRET_LEN + 1] = "L68wCVXYUaNg1Ey9";
char _device_name[IOTX_DEVICE_NAME_LEN + 1] = "example1";
char _device_secret[IOTX_DEVICE_SECRET_LEN + 1] = "";
#else
#ifdef DEVICE_MODEL_ENABLED
char _product_key[IOTX_PRODUCT_KEY_LEN + 1] = "a1RIsMLz2BJ";
char _product_secret[IOTX_PRODUCT_SECRET_LEN + 1] = "fSAF0hle6xL0oRWd";
char _device_name[IOTX_DEVICE_NAME_LEN + 1] = "example1";
char _device_secret[IOTX_DEVICE_SECRET_LEN + 1] = "RDXf67itLqZCwdMCRrw0N5FHbv5D7jrE";
#else
char _product_key[IOTX_PRODUCT_KEY_LEN + 1] = "a1MZxOdcBnO";
char _product_secret[IOTX_PRODUCT_SECRET_LEN + 1] = "h4I4dneEFp7EImTv";
char _device_name[IOTX_DEVICE_NAME_LEN + 1] = "test_01";
char _device_secret[IOTX_DEVICE_SECRET_LEN + 1] = "t9GmMf2jb3LgWfXBaZD2r3aJrfVWBv56";
#endif
#endif
char _firmware_version[IOTX_FIRMWARE_VER_LEN] = "app-1.0.0-20180101.1000";
void *HAL_Malloc(uint32_t size)
{
return malloc(size);
}
void *HAL_Realloc(void *ptr, uint32_t size)
{
return realloc(ptr, size);
}
void HAL_Free(void *ptr)
{
free(ptr);
}
uint64_t HAL_UptimeMs(void)
{
uint64_t time_ms;
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
time_ms = ((uint64_t)ts.tv_sec * (uint64_t)1000) + (ts.tv_nsec / 1000 / 1000);
return time_ms;
}
void HAL_SleepMs(uint32_t ms)
{
usleep(1000 * ms);
}
void HAL_Srandom(uint32_t seed)
{
srandom(seed);
}
uint32_t HAL_Random(uint32_t region)
{
FILE *handle;
ssize_t ret = 0;
uint32_t output = 0;
handle = fopen("/dev/urandom", "r");
if (handle == NULL) {
printf("open /dev/urandom failed\n");
return 0;
}
ret = fread(&output, sizeof(uint32_t), 1, handle);
if (ret != 1) {
printf("fread error: %d\n", (int)ret);
fclose(handle);
return 0;
}
fclose(handle);
return (region > 0) ? (output % region) : 0;
}
int HAL_Snprintf(char *str, const int len, const char *fmt, ...)
{
va_list args;
int rc;
va_start(args, fmt);
rc = vsnprintf(str, len, fmt, args);
va_end(args);
return rc;
}
int HAL_Vsnprintf(char *str, const int len, const char *format, va_list ap)
{
return vsnprintf(str, len, format, ap);
}
void HAL_Printf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
fflush(stdout);
}
int HAL_GetPartnerID(char *pid_str)
{
memset(pid_str, 0x0, IOTX_PARTNER_ID_LEN);
strcpy(pid_str, "c-sdk-2.3.0-pid");
return strlen(pid_str);
}
int HAL_GetModuleID(char *mid_str)
{
memset(mid_str, 0x0, IOTX_MODULE_ID_LEN);
strcpy(mid_str, "c-sdk-2.3.0-mid");
return strlen(mid_str);
}
int HAL_SetProductKey(char *product_key)
{
int len = strlen(product_key);
if (len > IOTX_PRODUCT_KEY_LEN) {
return -1;
}
memset(_product_key, 0x0, IOTX_PRODUCT_KEY_LEN + 1);
strncpy(_product_key, product_key, len);
return len;
}
int HAL_SetDeviceName(char *device_name)
{
int len = strlen(device_name);
if (len > IOTX_DEVICE_NAME_LEN) {
return -1;
}
memset(_device_name, 0x0, IOTX_DEVICE_NAME_LEN + 1);
strncpy(_device_name, device_name, len);
return len;
}
int HAL_SetProductSecret(char *product_secret)
{
int len = strlen(product_secret);
if (len > IOTX_PRODUCT_SECRET_LEN) {
return -1;
}
memset(_product_secret, 0x0, IOTX_PRODUCT_SECRET_LEN + 1);
strncpy(_product_secret, product_secret, len);
return len;
}
int HAL_SetDeviceSecret(char *device_secret)
{
int len = strlen(device_secret);
if (len > IOTX_DEVICE_SECRET_LEN) {
return -1;
}
memset(_device_secret, 0x0, IOTX_DEVICE_SECRET_LEN + 1);
strncpy(_device_secret, device_secret, len);
return len;
}
int HAL_GetProductKey(char product_key[IOTX_PRODUCT_KEY_LEN + 1])
{
int len = strlen(_product_key);
memset(product_key, 0x0, IOTX_PRODUCT_KEY_LEN + 1);
strncpy(product_key, _product_key, len);
return len;
}
int HAL_GetProductSecret(char product_secret[IOTX_PRODUCT_SECRET_LEN + 1])
{
int len = strlen(_product_secret);
memset(product_secret, 0x0, IOTX_PRODUCT_SECRET_LEN + 1);
strncpy(product_secret, _product_secret, len);
return len;
}
int HAL_GetDeviceName(char device_name[IOTX_DEVICE_NAME_LEN + 1])
{
int len = strlen(_device_name);
memset(device_name, 0x0, IOTX_DEVICE_NAME_LEN + 1);
strncpy(device_name, _device_name, len);
return strlen(device_name);
}
int HAL_GetDeviceSecret(char device_secret[IOTX_DEVICE_SECRET_LEN + 1])
{
int len = strlen(_device_secret);
memset(device_secret, 0x0, IOTX_DEVICE_SECRET_LEN + 1);
strncpy(device_secret, _device_secret, len);
return len;
}
void HAL_Reboot(void)
{
if (system("reboot")) {
perror("HAL_Reboot failed");
}
}
#define ROUTER_INFO_PATH "/proc/net/route"
#define ROUTER_RECORD_SIZE 256
char *_get_default_routing_ifname(char *ifname, int ifname_size)
{
FILE *fp = NULL;
char line[ROUTER_RECORD_SIZE] = {0};
char iface[IFNAMSIZ] = {0};
char *result = NULL;
unsigned int destination, gateway, flags, mask;
unsigned int refCnt, use, metric, mtu, window, irtt;
char *buff = NULL;
fp = fopen(ROUTER_INFO_PATH, "r");
if (fp == NULL) {
perror("fopen");
return result;
}
buff = fgets(line, sizeof(line), fp);
if (buff == NULL) {
perror("fgets");
goto out;
}
while (fgets(line, sizeof(line), fp)) {
if (11 !=
sscanf(line, "%s %08x %08x %x %d %d %d %08x %d %d %d",
iface, &destination, &gateway, &flags, &refCnt, &use,
&metric, &mask, &mtu, &window, &irtt)) {
perror("sscanf");
continue;
}
/*default route */
if ((destination == 0) && (mask == 0)) {
strncpy(ifname, iface, ifname_size - 1);
result = ifname;
break;
}
}
out:
if (fp) {
fclose(fp);
}
return result;
}
uint32_t HAL_Wifi_Get_IP(char ip_str[NETWORK_ADDR_LEN], const char *ifname)
{
struct ifreq ifreq;
int sock = -1;
char ifname_buff[IFNAMSIZ] = {0};
if ((NULL == ifname || strlen(ifname) == 0) &&
NULL == (ifname = _get_default_routing_ifname(ifname_buff, sizeof(ifname_buff)))) {
perror("get default routeing ifname");
return -1;
}
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
perror("socket");
return -1;
}
ifreq.ifr_addr.sa_family = AF_INET;
strncpy(ifreq.ifr_name, ifname, IFNAMSIZ - 1);
if (ioctl(sock, SIOCGIFADDR, &ifreq) < 0) {
close(sock);
perror("ioctl");
return -1;
}
close(sock);
strncpy(ip_str,
inet_ntoa(((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr),
NETWORK_ADDR_LEN);
return ((struct sockaddr_in *)&ifreq.ifr_addr)->sin_addr.s_addr;
}
int HAL_GetFirmwareVersion(char *version)
{
char *ver = "app-1.0.0-20180101.1000";
int len = strlen(ver);
memset(version, 0x0, IOTX_FIRMWARE_VER_LEN);
strncpy(version, ver, IOTX_FIRMWARE_VER_LEN);
version[len] = '\0';
return strlen(version);
}
void *HAL_SemaphoreCreate(void)
{
sem_t *sem = (sem_t *)malloc(sizeof(sem_t));
if (NULL == sem) {
return NULL;
}
if (0 != sem_init(sem, 0, 0)) {
free(sem);
return NULL;
}
return sem;
}
void HAL_SemaphoreDestroy(void *sem)
{
sem_destroy((sem_t *)sem);
free(sem);
}
void HAL_SemaphorePost(void *sem)
{
sem_post((sem_t *)sem);
}
int HAL_SemaphoreWait(void *sem, uint32_t timeout_ms)
{
if (PLATFORM_WAIT_INFINITE == timeout_ms) {
sem_wait(sem);
return 0;
} else {
struct timespec ts;
int s;
/* Restart if interrupted by handler */
do {
if (clock_gettime(CLOCK_REALTIME, &ts) == -1) {
return -1;
}
s = 0;
ts.tv_nsec += (timeout_ms % 1000) * 1000000;
if (ts.tv_nsec >= 1000000000) {
ts.tv_nsec -= 1000000000;
s = 1;
}
ts.tv_sec += timeout_ms / 1000 + s;
} while (((s = sem_timedwait(sem, &ts)) != 0) && errno == EINTR);
return (s == 0) ? 0 : -1;
}
}
int HAL_ThreadCreate(
void **thread_handle,
void *(*work_routine)(void *),
void *arg,
hal_os_thread_param_t *hal_os_thread_param,
int *stack_used)
{
int ret = -1;
if (stack_used) {
*stack_used = 0;
}
ret = pthread_create((pthread_t *)thread_handle, NULL, work_routine, arg);
return ret;
}
void HAL_ThreadDetach(void *thread_handle)
{
pthread_detach((pthread_t)thread_handle);
}
void HAL_ThreadDelete(void *thread_handle)
{
if (NULL == thread_handle) {
pthread_exit(0);
} else {
/*main thread delete child thread*/
pthread_cancel((pthread_t)thread_handle);
pthread_join((pthread_t)thread_handle, 0);
}
}
static FILE *fp;
#define otafilename "/tmp/alinkota.bin"
void HAL_Firmware_Persistence_Start(void)
{
fp = fopen(otafilename, "w");
return;
}
int HAL_Firmware_Persistence_Write(char *buffer, uint32_t length)
{
unsigned int written_len = 0;
written_len = fwrite(buffer, 1, length, fp);
if (written_len != length) {
return -1;
}
return 0;
}
int HAL_Firmware_Persistence_Stop(void)
{
if (fp != NULL) {
fclose(fp);
}
/* check file md5, and burning it to flash ... finally reboot system */
return 0;
}
void *HAL_MutexCreate(void)
{
int err_num;
pthread_mutex_t *mutex = (pthread_mutex_t *)HAL_Malloc(sizeof(pthread_mutex_t));
if (NULL == mutex) {
return NULL;
}
if (0 != (err_num = pthread_mutex_init(mutex, NULL))) {
printf("create mutex failed\n");
HAL_Free(mutex);
return NULL;
}
return mutex;
}
void HAL_MutexDestroy(void *mutex)
{
int err_num;
if (!mutex) {
printf("mutex want to destroy is NULL!\n");
return;
}
if (0 != (err_num = pthread_mutex_destroy((pthread_mutex_t *)mutex))) {
printf("destroy mutex failed\n");
}
HAL_Free(mutex);
}
void HAL_MutexLock(void *mutex)
{
int err_num;
if (0 != (err_num = pthread_mutex_lock((pthread_mutex_t *)mutex))) {
printf("lock mutex failed: - '%s' (%d)\n", strerror(err_num), err_num);
}
}
void HAL_MutexUnlock(void *mutex)
{
int err_num;
if (0 != (err_num = pthread_mutex_unlock((pthread_mutex_t *)mutex))) {
printf("unlock mutex failed - '%s' (%d)\n", strerror(err_num), err_num);
}
}
void *HAL_Timer_Create(const char *name, void (*func)(void *), void *user_data)
{
timer_t *timer = NULL;
struct sigevent ent;
/* check parameter */
if (func == NULL) {
return NULL;
}
timer = (timer_t *)malloc(sizeof(time_t));
if (timer == NULL) {
return NULL;
}
/* Init */
memset(&ent, 0x00, sizeof(struct sigevent));
/* create a timer */
ent.sigev_notify = SIGEV_THREAD;
ent.sigev_notify_function = (void (*)(union sigval))func;
ent.sigev_value.sival_ptr = user_data;
printf("HAL_Timer_Create\n");
if (timer_create(CLOCK_MONOTONIC, &ent, timer) != 0) {
free(timer);
return NULL;
}
return (void *)timer;
}
int HAL_Timer_Start(void *timer, int ms)
{
struct itimerspec ts;
/* check parameter */
if (timer == NULL) {
return -1;
}
/* it_interval=0: timer run only once */
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 0;
/* it_value=0: stop timer */
ts.it_value.tv_sec = ms / 1000;
ts.it_value.tv_nsec = (ms % 1000) * 1000000;
return timer_settime(*(timer_t *)timer, 0, &ts, NULL);
}
int HAL_Timer_Stop(void *timer)
{
struct itimerspec ts;
/* check parameter */
if (timer == NULL) {
return -1;
}
/* it_interval=0: timer run only once */
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 0;
/* it_value=0: stop timer */
ts.it_value.tv_sec = 0;
ts.it_value.tv_nsec = 0;
return timer_settime(*(timer_t *)timer, 0, &ts, NULL);
}
int HAL_Timer_Delete(void *timer)
{
int ret = 0;
/* check parameter */
if (timer == NULL) {
return -1;
}
ret = timer_delete(*(timer_t *)timer);
free(timer);
return ret;
}
int HAL_GetNetifInfo(char *nif_str)
{
const char *net_info = "WiFi|03ACDEFF0032";
memset(nif_str, 0x0, IOTX_NETWORK_IF_LEN);
/* if the device have only WIFI, then list as follow, note that the len MUST NOT exceed NIF_STRLEN_MAX */
strncpy(nif_str, net_info, IOTX_NETWORK_IF_LEN);
/* if the device have ETH, WIFI, GSM connections, then list all of them as follow, note that the len MUST NOT exceed NIF_STRLEN_MAX */
/* const char *multi_net_info = "ETH|0123456789abcde|WiFi|03ACDEFF0032|Cellular|imei_0123456789abcde|iccid_0123456789abcdef01234|imsi_0123456789abcde|msisdn_86123456789ab"); */
/* strncpy(nif_str, multi_net_info, strlen(multi_net_info)); */
return strlen(nif_str);
}

View File

@@ -0,0 +1,269 @@
/*
* 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;
}

View File

@@ -0,0 +1,218 @@
#include <stdint.h>
#include <errno.h>
#if defined(__UBUNTU_SDK_DEMO__)
#include <execinfo.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <sys/select.h>
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <assert.h>
#include "infra_config.h"
#include "at_parser.h"
#include "at_wrapper.h"
static int at_uart_fd = -1;
static int read_and_discard_all_data(const int fd)
{
int was_msg_already_printed = 0;
int errno_code;
while (1) {
char buffer[1024];
const ssize_t read_count = read(fd, buffer, sizeof(buffer));
if (read_count == 0) {
/* "EOF" or "connection closed at the other end"*/
return 0;
}
if (read_count > 0) {
if (!was_msg_already_printed) {
printf("Some stale data was discarded.\r\n");
was_msg_already_printed = 1;
}
continue;
}
assert(read_count == -1); /* According to the specification. */
errno_code = errno;
if (errno_code == EINTR) {
continue;
}
if (errno_code == EAGAIN ||
errno_code == EWOULDBLOCK) {
/**
* We know that the file descriptor has been opened with
* O_NONBLOCK or O_NDELAY, and these codes mean that there
* is no data to read at present.
*/
return 0;
}
/* Some other error has occurred. */
return -1;
}
}
int32_t HAL_AT_Uart_Init(uart_dev_t *uart)
{
int fd;
struct termios t_opt;
speed_t baud;
if (uart->port != AT_UART_PORT) {
return 0;
}
if ((at_uart_fd = open(AT_UART_LINUX_DEV,
O_RDWR | O_NOCTTY | O_NDELAY)) == -1) {
printf("open at uart failed\r\n");
return -1;
}
switch (uart->config.baud_rate) {
case 115200:
baud = B115200;
break;
case 921600:
baud = B921600;
break;
default:
baud = B115200;
break;
}
fd = at_uart_fd;
/* set the serial port parameters */
fcntl(fd, F_SETFL, 0);
if (0 != tcgetattr(fd, &t_opt)) {
return -1;
}
if (0 != cfsetispeed(&t_opt, baud)) {
return -1;
}
if (0 != cfsetospeed(&t_opt, baud)) {
return -1;
}
/* 8N1, flow control, etc. */
t_opt.c_cflag |= (CLOCAL | CREAD);
if (uart->config.parity == NO_PARITY) {
t_opt.c_cflag &= ~PARENB;
}
if (uart->config.stop_bits == STOP_BITS_1) {
t_opt.c_cflag &= ~CSTOPB;
} else {
t_opt.c_cflag |= CSTOPB;
}
t_opt.c_cflag &= ~CSIZE;
switch (uart->config.data_width) {
case DATA_WIDTH_5BIT:
t_opt.c_cflag |= CS5;
break;
case DATA_WIDTH_6BIT:
t_opt.c_cflag |= CS6;
break;
case DATA_WIDTH_7BIT:
t_opt.c_cflag |= CS7;
break;
case DATA_WIDTH_8BIT:
t_opt.c_cflag |= CS8;
break;
default:
t_opt.c_cflag |= CS8;
break;
}
t_opt.c_lflag &= ~(ECHO | ECHOE | ISIG | ICANON);
/**
* AT is going to use a binary protocol, so make sure to
* turn off any CR/LF translation and the like.
*/
t_opt.c_iflag &= ~(IXON | IXOFF | IXANY | INLCR | ICRNL);
t_opt.c_oflag &= ~OPOST;
t_opt.c_cc[VMIN] = 0;
t_opt.c_cc[VTIME] = 5;
if (0 != tcsetattr(fd, TCSANOW, &t_opt)) {
return -1;
}
printf("open at uart succeed\r\n");
/* clear uart buffer */
read_and_discard_all_data(fd);
return 0;
}
int32_t HAL_AT_Uart_Deinit(uart_dev_t *uart)
{
if (uart->port == AT_UART_PORT) {
close(at_uart_fd);
}
return 0;
}
int32_t HAL_AT_Uart_Send(uart_dev_t *uart, const void *data,
uint32_t size, uint32_t timeout)
{
uint32_t ret, rmd = size;
if (uart->port == AT_UART_PORT) {
while (rmd > 0) {
ret = write(at_uart_fd, data + size - rmd, rmd);
if (ret == -1) {
printf("write uart fd failed on error: %d.\r\n", errno);
return -1;
}
rmd -= ret;
}
} else {
if (write(1, data, size) < 0) {
printf("write failed\n");
}
}
return 0;
}
int32_t HAL_AT_Uart_Recv(uart_dev_t *uart, void *data, uint32_t expect_size,
uint32_t *recv_size, uint32_t timeout)
{
int fd, n;
if (uart->port == AT_UART_PORT) {
fd = at_uart_fd;
} else {
fd = 1;
}
if ((n = read(fd, data, expect_size)) == -1) {
return -1;
}
if (uart->port != AT_UART_PORT && *(char *)data == '\n') {
*(char *)data = '\r';
}
if (recv_size) {
*recv_size = n;
}
return 0;
}

View File

@@ -0,0 +1,375 @@
#include "infra_config.h"
#if defined(HAL_UDP)
/*
* Copyright (C) 2015-2018 Alibaba Group Holding Limited
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <pthread.h>
#include "infra_config.h"
#include "infra_compat.h"
intptr_t HAL_UDP_create(char *host, unsigned short port)
{
#define NETWORK_ADDR_LEN (16)
int rc = -1;
long socket_id = -1;
char port_ptr[6] = {0};
struct addrinfo hints;
char addr[NETWORK_ADDR_LEN] = {0};
struct addrinfo *res, *ainfo;
struct sockaddr_in *sa = NULL;
if (NULL == host) {
return (-1);
}
sprintf(port_ptr, "%u", port);
memset((char *)&hints, 0x00, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = AF_INET;
hints.ai_protocol = IPPROTO_UDP;
rc = getaddrinfo(host, port_ptr, &hints, &res);
if (0 != rc) {
printf("getaddrinfo error");
return (-1);
}
for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
if (AF_INET == ainfo->ai_family) {
sa = (struct sockaddr_in *)ainfo->ai_addr;
inet_ntop(AF_INET, &sa->sin_addr, addr, NETWORK_ADDR_LEN);
fprintf(stderr, "The host IP %s, port is %d\r\n", addr, ntohs(sa->sin_port));
socket_id = socket(ainfo->ai_family, ainfo->ai_socktype, ainfo->ai_protocol);
if (socket_id < 0) {
printf("create socket error");
continue;
}
if (0 == connect(socket_id, ainfo->ai_addr, ainfo->ai_addrlen)) {
break;
}
close(socket_id);
}
}
freeaddrinfo(res);
return socket_id;
#undef NETWORK_ADDR_LEN
}
void HAL_UDP_close(intptr_t p_socket)
{
long socket_id = -1;
socket_id = p_socket;
close(socket_id);
}
int HAL_UDP_write(intptr_t p_socket,
const unsigned char *p_data,
unsigned int datalen)
{
int rc = -1;
long socket_id = -1;
socket_id = (long)p_socket;
rc = send(socket_id, (char *)p_data, (int)datalen, 0);
if (-1 == rc) {
return -1;
}
return rc;
}
int HAL_UDP_readTimeout(intptr_t p_socket,
unsigned char *p_data,
unsigned int datalen,
unsigned int timeout)
{
int ret;
struct timeval tv;
fd_set read_fds;
long socket_id = -1;
if (0 == p_socket || NULL == p_data) {
return -1;
}
socket_id = (long)p_socket;
if (socket_id < 0) {
return -1;
}
FD_ZERO(&read_fds);
FD_SET(socket_id, &read_fds);
tv.tv_sec = timeout / 1000;
tv.tv_usec = (timeout % 1000) * 1000;
ret = select(socket_id + 1, &read_fds, NULL, NULL, timeout == 0 ? NULL : &tv);
/* Zero fds ready means we timed out */
if (ret == 0) {
return -2; /* receive timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want read */
}
return -4; /* receive failed */
}
/* This call will not block */
return read(p_socket, p_data, datalen);
}
intptr_t HAL_UDP_create_without_connect(const char *host, unsigned short port)
{
struct sockaddr_in addr;
long sockfd;
int opt_val = 1;
struct hostent *hp;
struct in_addr in;
uint32_t ip;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
printf("socket");
return -1;
}
if (0 == port) {
return (intptr_t)sockfd;
}
memset(&addr, 0, sizeof(struct sockaddr_in));
if (0 != setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_BROADCAST, &opt_val, sizeof(opt_val))) {
printf("setsockopt");
close(sockfd);
return -1;
}
if (NULL == host) {
addr.sin_addr.s_addr = htonl(INADDR_ANY);
} else {
if (inet_aton(host, &in)) {
ip = *(uint32_t *)&in;
} else {
hp = gethostbyname(host);
if (!hp) {
printf("can't resolute the host address \n");
close(sockfd);
return -1;
}
ip = *(uint32_t *)(hp->h_addr);
}
addr.sin_addr.s_addr = ip;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
if (-1 == bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in))) {
close(sockfd);
return -1;
}
printf("success to establish udp, fd=%d", (int)sockfd);
return (intptr_t)sockfd;
}
int HAL_UDP_connect(intptr_t sockfd,
const char *host,
unsigned short port)
{
int rc = -1;
char port_ptr[6] = {0};
struct addrinfo hints;
struct addrinfo *res, *ainfo;
if (NULL == host) {
return -1;
}
printf("HAL_UDP_connect, host=%s, port=%d", host, port);
sprintf(port_ptr, "%u", port);
memset((char *)&hints, 0x00, sizeof(hints));
hints.ai_socktype = SOCK_DGRAM;
hints.ai_family = AF_INET;
hints.ai_protocol = IPPROTO_UDP;
rc = getaddrinfo(host, port_ptr, &hints, &res);
if (0 != rc) {
printf("getaddrinfo error");
return -1;
}
for (ainfo = res; ainfo != NULL; ainfo = ainfo->ai_next) {
if (AF_INET == ainfo->ai_family) {
if (0 == connect(sockfd, ainfo->ai_addr, ainfo->ai_addrlen)) {
freeaddrinfo(res);
return 0;
}
}
}
freeaddrinfo(res);
return -1;
}
int HAL_UDP_close_without_connect(intptr_t sockfd)
{
return close((int)sockfd);
}
int HAL_UDP_joinmulticast(intptr_t sockfd,
char *p_group)
{
int err = -1;
int socket_id = -1;
int loop = 0;
struct ip_mreq mreq;
if (NULL == p_group) {
return -1;
}
/*set loopback*/
socket_id = (int)sockfd;
err = setsockopt(socket_id, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop));
if (err < 0) {
printf("setsockopt");
return err;
}
mreq.imr_multiaddr.s_addr = inet_addr(p_group);
mreq.imr_interface.s_addr = htonl(INADDR_ANY); /*default networt interface*/
/*join to the multicast group*/
err = setsockopt(socket_id, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
if (err < 0) {
printf("setsockopt");
return err;
}
return 0;
}
int HAL_UDP_recvfrom(intptr_t sockfd,
NetworkAddr *p_remote,
unsigned char *p_data,
unsigned int datalen,
unsigned int timeout_ms)
{
int ret;
struct sockaddr_in addr;
socklen_t addr_len = sizeof(addr);
fd_set read_fds;
struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
FD_ZERO(&read_fds);
FD_SET(sockfd, &read_fds);
ret = select(sockfd + 1, &read_fds, NULL, NULL, &timeout);
if (ret == 0) {
return 0; /* receive timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want read */
}
return -4; /* receive failed */
}
ret = recvfrom(sockfd, p_data, datalen, 0, (struct sockaddr *)&addr, &addr_len);
if (ret > 0) {
if (NULL != p_remote) {
p_remote->port = ntohs(addr.sin_port);
strcpy((char *)p_remote->addr, inet_ntoa(addr.sin_addr));
}
return ret;
}
return -1;
}
int HAL_UDP_sendto(intptr_t sockfd,
const NetworkAddr *p_remote,
const unsigned char *p_data,
unsigned int datalen,
unsigned int timeout_ms)
{
int ret;
uint32_t ip;
struct in_addr in;
struct hostent *hp;
struct sockaddr_in addr;
fd_set write_fds;
struct timeval timeout = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
if (inet_aton((char *)p_remote->addr, &in)) {
ip = *(uint32_t *)&in;
} else {
hp = gethostbyname((char *)p_remote->addr);
if (!hp) {
printf("can't resolute the host address \n");
return -1;
}
ip = *(uint32_t *)(hp->h_addr);
}
FD_ZERO(&write_fds);
FD_SET(sockfd, &write_fds);
ret = select(sockfd + 1, NULL, &write_fds, NULL, &timeout);
if (ret == 0) {
return 0; /* write timeout */
}
if (ret < 0) {
if (errno == EINTR) {
return -3; /* want write */
}
return -4; /* write failed */
}
addr.sin_addr.s_addr = ip;
addr.sin_family = AF_INET;
addr.sin_port = htons(p_remote->port);
ret = sendto(sockfd, p_data, datalen, 0, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
if (ret < 0) {
printf("sendto");
}
return (ret) > 0 ? ret : -1;
}
#endif /* #if defined(HAL_UDP) */