#if defined(WIN32) || defined(WIN64)
#include "windows.h"
#include "io.h"
#else
#include "unistd.h"
#endif
#include <stdlib.h>
#include <openssl/ossl_typ.h>
#include <openssl/hmac.h>
#include "MQTTAsync.h"
#include "string.h"
#include "string_util.h"
char *uri = "tcp://iot-mqtts.cn-north-4.myhuaweicloud.com:1883";
int port = 1883;
char *username = "5ee988f32bd89f02e9720561_981637988"; //deviceId or nodeId
//char *username = "test6789";
char *password = "11111111";
int gQOS = 1; //default value of qos is 1
int keepAliveInterval = 120; //default value of keepAliveInterval is 120s
int connectTimeout = 30; //default value of connect timeout is 30s
int retryInterval = 10; //default value of connect retryInterval is 10s
char *ca_path = "./conf/rootcert.pem";
MQTTAsync client = NULL;
int flag = 0; //0: deviceId access; 1:nodeId access, just for old mqtt api.
#define TRY_MAX_TIME 100 //Maximum length of attempted encryption
#define SHA256_ENCRYPTION_LENGRH 32
#define TIME_STAMP_LENGTH 10
#define PASSWORD_ENCRYPT_LENGTH 64
int mqttClientCreateFlag = 0; //this mqttClientCreateFlag is used to control the invocation of MQTTAsync_create, otherwise, there would be message leak.
void mqtt_connect_success(void *context, MQTTAsync_successData *response) {
printf("connect success. \n");
}
void mqtt_connect_failure(void *context, MQTTAsync_failureData *response) {
printf("connect failed: messageId %d, code %d, message %s\n", response->token, response->code, response->message);
}
int EncryWithHMacSha256(const char *inputData, char **inputKey, int inEncryDataLen, char *outData) {
if (inputData == NULL || (*inputKey) == NULL) {
printf("encryWithHMacSha256(): the input is invalid.\n");
return -1;
}
if (TIME_STAMP_LENGTH != strlen(*inputKey)) {
printf("encryWithHMacSha256(): the length of inputKey is invalid.\n");
return -1;
}
char *end = NULL;
unsigned int mac_length = 0;
unsigned int tryTime = 1;
int lenData = strlen(inputData);
long timeTmp = strtol(*inputKey, &end, 10);
unsigned char *temp = HMAC(EVP_sha256(), *inputKey, TIME_STAMP_LENGTH, (const unsigned char*) inputData, lenData, NULL, &mac_length);
while (strlen(temp) != SHA256_ENCRYPTION_LENGRH) {
tryTime++;
if (tryTime > TRY_MAX_TIME) {
printf("encryWithHMacSha256(): Encryption failed after max times attempts.\n");
return -1;
}
timeTmp++;
snprintf(*inputKey, TIME_STAMP_LENGTH + 1, "%ld", timeTmp);
temp = HMAC(EVP_sha256(), *inputKey, TIME_STAMP_LENGTH, (const unsigned char*) inputData, lenData, NULL, &mac_length);
}
int uiIndex, uiLoop;
char ucHex;
for (uiIndex = 0, uiLoop = 0; uiLoop < inEncryDataLen; uiLoop++) {
ucHex = (temp[uiLoop] >> 4) & 0x0F;
outData[uiIndex++] = (ucHex <= 9) ? (ucHex + '0') : (ucHex + 'a' - 10);
ucHex = temp[uiLoop] & 0x0F;
outData[uiIndex++] = (ucHex <= 9) ? (ucHex + '0') : (ucHex + 'a' - 10);
}
outData[uiIndex] = '\0';
return 0;
}
int GetEncryptedPassword(char **timestamp, char **encryptedPwd) {
if (password == NULL) {
return -1;
}
char *temp_encrypted_pwd = NULL;
string_malloc(&temp_encrypted_pwd, PASSWORD_ENCRYPT_LENGTH + 1);
if (temp_encrypted_pwd == NULL) {
printf("GetEncryptedPassword() error, there is not enough memory here.\n");
return -1;
}
int ret = EncryWithHMacSha256(password, timestamp, SHA256_ENCRYPTION_LENGRH, temp_encrypted_pwd);
if (ret != 0) {
printf( "GetEncryptedPassword() error, encrypt failed %d\n", ret);
free(temp_encrypted_pwd);
temp_encrypted_pwd = NULL;
return -1;
}
if (CopyStrValue(encryptedPwd, (const char*) temp_encrypted_pwd, PASSWORD_ENCRYPT_LENGTH) < 0) {
printf("GetEncryptedPassword(): there is not enough memory here.\n");
free(temp_encrypted_pwd);
temp_encrypted_pwd = NULL;
return -1;
}
free(temp_encrypted_pwd);
temp_encrypted_pwd = NULL;
return 0;
}
//receive message from the server
int mqtt_message_arrive(void *context, char *topicName, int topicLen, MQTTAsync_message *message) {
printf( "mqtt_message_arrive() success, the topic is %s, the payload is %s \n", topicName, message->payload);
return 1; //can not return 0 here, otherwise the message won't update or something wrong would happen
}
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer;
void mqtt_connection_lost(void *context, char *cause) {
printf("mqtt_connection_lost() error, cause: %s\n", cause);
}
int mqtt_connect() {
char *encrypted_password = NULL;
if (!mqttClientCreateFlag) {
char *temp_authMode = "_0_0_";
if (flag == 1) {
temp_authMode = "_2_0_";
}
conn_opts.cleansession = 1;
conn_opts.keepAliveInterval = keepAliveInterval;
conn_opts.connectTimeout = connectTimeout;
conn_opts.retryInterval = retryInterval;
conn_opts.onSuccess = mqtt_connect_success;
conn_opts.onFailure = mqtt_connect_failure;
char *loginTimestamp = get_client_timestamp();
if (loginTimestamp == NULL) {
return -1;
}
int encryptedRet = GetEncryptedPassword(&loginTimestamp, &encrypted_password);
if (encryptedRet != 0) {
free(loginTimestamp);
loginTimestamp = NULL;
return -1;
}
if(port == 8883) {
if (access(ca_path, 0)) {
printf("ca file is NOT accessible\n");
free(loginTimestamp);
loginTimestamp = NULL;
return -1;
}
ssl_opts.trustStore = ca_path;
ssl_opts.enabledCipherSuites = "TLSv1.2";
ssl_opts.enableServerCertAuth = 1; // 1: enable server certificate authentication, 0: disable
// ssl_opts.verify = 0; // 0 for no verifying the hostname, 1 for verifying the hostname
conn_opts.ssl = &ssl_opts;
}
char *clientId = NULL;
clientId = combine_strings(3, username, temp_authMode, loginTimestamp);
free(loginTimestamp);
loginTimestamp = NULL;
int createRet = MQTTAsync_create(&client, uri, clientId, MQTTCLIENT_PERSISTENCE_NONE, NULL);
free(clientId);
clientId = NULL;
if (createRet) {
printf("mqtt_connect() MQTTAsync_create error, result %d\n", createRet);
} else {
mqttClientCreateFlag = 1;
printf("mqtt_connect() mqttClientCreateFlag = 1.\n");
}
MQTTAsync_setCallbacks(client, NULL, mqtt_connection_lost, mqtt_message_arrive, NULL);
}
conn_opts.username = username;
conn_opts.password = encrypted_password;
printf("begin to connect the server.\n");
int ret = MQTTAsync_connect(client, &conn_opts);
if (ret) {
printf("mqtt_connect() error, result %d\n", ret);
return -1;
}
if (encrypted_password != NULL) {
free(encrypted_password);
encrypted_password = NULL;
}
return 0;
}
void publish_success(void *context, MQTTAsync_successData *response) {
printf("publish success, the messageId is %d \n", response ? response->token : -1);
}
void publish_failure(void *context, MQTTAsync_failureData *response) {
printf("publish failure\n");
if(response) {
printf("publish_failure(), messageId is %d, code is %d, message is %s\n", response->token, response->code, response->message);
}
}
int mqtt_publish(const char *topic, char *payload) {
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
opts.onSuccess = publish_success;
opts.onFailure = publish_failure;
pubmsg.payload = payload;
pubmsg.payloadlen = (int) strlen(payload);
pubmsg.qos = gQOS;
pubmsg.retained = 0;
int ret = MQTTAsync_sendMessage(client, topic, &pubmsg, &opts);
if (ret != 0) {
printf( "mqtt_publish() error, publish result %d\n", ret);
return -1;
}
printf("mqtt_publish(), the payload is %s, the topic is %s \n", payload, topic);
return opts.token;
}
void subscribe_success(void *context, MQTTAsync_successData *response) {
printf("subscribe success, the messageId is %d \n", response ? response->token : -1);
}
void subscribe_failure(void *context, MQTTAsync_failureData *response) {
printf("subscribe failure\n");
if(response) {
printf("subscribe_failure(), messageId is %d, code is %d, message is %s\n", response->token,
没有合适的资源?快使用搜索试试~ 我知道了~
资源推荐
资源详情
资源评论
收起资源包目录
arm_mqtt_c_ok.zip (129个子文件)
libcrypto.so.1.1 2.43MB
libssl.so.1.1 542KB
libpaho-mqtt3as.so.1 488KB
libanl.so.1 19KB
mqtt_c_demo.c 9KB
string_util.c 2KB
mqtt_c_demo.d 11KB
string_util.d 6KB
obj_mac.h 212KB
ssl.h 109KB
MQTTAsync.h 86KB
MQTTClient.h 80KB
evp.h 75KB
tls1.h 71KB
ec.h 62KB
sslerr.h 46KB
x509.h 42KB
bio.h 34KB
engine.h 34KB
asn1.h 33KB
x509v3.h 33KB
asn1t.h 32KB
x509_vfy.h 31KB
ts.h 22KB
rsa.h 22KB
bn.h 22KB
crypto.h 17KB
cms.h 16KB
ui.h 16KB
ct.h 16KB
ecerr.h 15KB
pem.h 15KB
ocsp.h 15KB
asn1err.h 14KB
ssl3.h 14KB
dh.h 13KB
pkcs7.h 11KB
evperr.h 11KB
err.h 11KB
store.h 11KB
cmserr.h 11KB
modes.h 10KB
MQTTClientPersistence.h 10KB
dsa.h 10KB
pkcs12.h 10KB
MQTTProperties.h 9KB
lhash.h 9KB
rsaerr.h 9KB
e_os2.h 9KB
x509v3err.h 9KB
safestack.h 8KB
des.h 7KB
x509err.h 7KB
tserr.h 7KB
objects.h 6KB
bioerr.h 6KB
ossl_typ.h 6KB
conf.h 5KB
engineerr.h 5KB
pkcs7err.h 5KB
pemerr.h 5KB
bnerr.h 5KB
rand_drbg.h 5KB
randerr.h 5KB
opensslconf.h 5KB
storeerr.h 4KB
kdf.h 4KB
opensslv.h 4KB
dherr.h 4KB
sha.h 4KB
srp.h 4KB
pkcs12err.h 4KB
seed.h 3KB
cterr.h 3KB
conferr.h 3KB
ocsperr.h 3KB
aes.h 3KB
MQTTReasonCodes.h 3KB
camellia.h 3KB
stack.h 3KB
dsaerr.h 3KB
uierr.h 3KB
async.h 2KB
cryptoerr.h 2KB
rand.h 2KB
kdferr.h 2KB
idea.h 2KB
rc5.h 2KB
blowfish.h 2KB
MQTTSubscribeOpts.h 2KB
cast.h 2KB
txt_db.h 2KB
buffer.h 2KB
hmac.h 2KB
dtls1.h 2KB
rc2.h 1KB
whrlpool.h 1KB
comp.h 1KB
asyncerr.h 1KB
md4.h 1KB
共 129 条
- 1
- 2
资源评论
鸭鸭打瞌睡
- 粉丝: 559
- 资源: 13
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 193ssm网上花店AHB6程序.zip
- springboot032阿博图书馆管理系统.zip
- ssm美食推荐管理系统.zip
- 132ssm共享琴房平台hsg3973AFB4程序.zip
- ssm房屋出租出售系统.zip
- 035-java精品项目-在线购书商城系统.zip
- python 语言一个基于tensorflow 使用keras使用lstm实现的中文文本情感二分类文本多分类.zip
- springboot228高校教师电子名片系统.zip
- 155ssm中小学生学习平台.zip
- springboot642饮食分享平台--论文.zip
- springboot324电影订票及评论网站的设计与实现.zip
- MYLIBRARY图书管理系统 是基于Spring Boot Mybatis 开发的图书管理系统 系统具有用户管理角.zip
- 525家具销售电商平台.zip
- ssm621大湾区旅游推荐系统的设计与实现vue.zip
- 医院预约挂号系统1.zip
- SSM作业管理系统.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功