blob: e350c9047f8845ef3fd6dd8acfc3e85fc218e5b2 [file] [log] [blame]
/****************************************************************************
*
****************************************************************************/
#include <stdio.h>
#include "string.h"
#include "dongle_cmd.h"
#include "dongle_cust.h"
#include "dongle_dmp.h"
#include "MQTTClient.h"
#include <pthread.h>
#include <time.h>
#include <semaphore.h>
#include "util_sha256.h"
#include "util_string.h"
#include "cJSON.h"
#include "cfg_api.h"
#include "zte_web_lan.h"
#include <curl/curl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "softap_log.h"
#define DMP_TOKEN_FILE "/mnt/userdata/dongle_dmp_token"
#define DONGLE_DMP_CONFIG "/mnt/userdata/dongle_dmp_config"
#define PRODUCT_KEY "cuj28lghju3q5Bha"
#define MQTT_RECONN_MINTIMESPACE (1*60*1000) //Reconnect min timespace, unit:ms
#define MQTT_RECONN_MAXCOUNT (30) //Reconnect max count
#define DMP_HOST "dmp-mqtts.cuiot.cn"
#define DMP_PORT 8883
typedef enum
{
LYNQ_FOTA_BEGIN = 0, //FOTA begin http download
LYNQ_FOTA_DL_PROC = 1, //FOTA download progress
LYNQ_FOTA_ERR = 2, //FOTA error
LYNQ_FOTA_DOWNLOADEND = 3, //FOTA download end
LYNQ_FOTA_PACKAGE_MISMATCH = 4, //FOTA package mismatch
LYNQ_FOTA_PARAM_ERRR = 5 //FOTA param error
} lynq_fota_status;
lynq_dmp_cfg_t dmp_repo_config;
//
int dmp_repo_time = MBTK_DMP_REPO_TIME;
char productSecret[50] = {0};
char productKey[50] = {0};
char g_TokenStr[64 + 1] = {0};
static char dmp_MqttSendbuf[1024];
static char dmp_MqttReadbuf[1024];
static Network dmp_MqttNetwork;
static MQTTClient dmp_MqttClient;
int arrived_flag = 0;
static int sim_type_flag = 0;
static int message_id = 123;
MQTTPacket_connectData connectData2 = MQTTPacket_connectData_initializer;
char *connackReturnCodeStr[] = {"success",
"unnacceptable protocol",
"clientid rejected",
"server unavailable",
"bad username or password",
"not authorized"};
volatile int toStop = 0;
void mbtk_dmp_repo_msg(void);
int mbtk_subscribe_topic();
/**
* @brief Gets the value of nv
*
* Based on the given nv name, get the corresponding value from the configuration file and store it in the specified string variable.
*
* @param key nv name
* @param value A string variable that stores the value of nv
*
* @return If 1 is returned, the value of nv is obtained successfully. Otherwise, other values are returned
*/
int get_cfg_item(char* key,char* value)
{
char rstr[36] = {0};
cfg_get_item(key, rstr, sizeof(rstr));
slog(MISC_PRINT, SLOG_DEBUG, "nv get %s = %s",key,rstr);
//printf("nv get %s = %s",key,rstr);
if(strlen(rstr) > 0)
{
strcpy(value, rstr);
}
return 1;
}
void trim_version(const char* input, char* output, size_t outputSize) {
const char* searchFor = "AP";
const char delimiter = '.';
const char* apPos = strstr(input, searchFor);
if (apPos != NULL) {
// Skip AP and the first . immediately following it.
apPos += strlen(searchFor) + 1; // Plus the length of the AP and a .
// the base string to be concatenated
const char* prefix = "R305V";
// Check if the remaining space is sufficient
size_t prefixLen = strlen(prefix);
size_t versionLen = 0;
while (*apPos != '\0' && versionLen < outputSize) {
versionLen++;
apPos++;
}
// Make sure there is enough space to store the results
if (prefixLen + versionLen + 1 > outputSize) {
*output = '\0';
return;
}
// Copy the base string to the output array
strcpy(output, prefix);
// Concatenate version number
strncpy(output + prefixLen, apPos - versionLen, versionLen); // 注意调整起始位置
output[prefixLen + versionLen] = '\0';
} else {
// If the AP is not found, the output array remains empty
*output = '\0';
}
printf("version is %s\n", output);
}
/**
* @brief Handle the MQTT inform_reply topic
*
* @param md Message data pointer
*/
void dmp_sub_command_handle(MessageData* md)
{
MQTTMessage* m = md->message;
// Check if the message payload contains "code"
if(strstr(m->payload, "code") != NULL)
{
char code[10] = {0};
char* strPtr = NULL;
strPtr = strstr(m->payload, "code");
strPtr = strPtr + 7;
// From the current position, read the string before the next double quotation mark and save it to the code array
sscanf(strPtr,"%[^\"]",code);
slog(MISC_PRINT, SLOG_DEBUG, "pub version code was %s\n", code);
//printf("pub version code was %s\n", code);
}
}
/**
* @brief Handle DMP remote upgrade
*
* parse the download link and the upgrade operation is performed.
*
* @param md Message data pointer
*/
void dmp_upgrade_handle(MessageData* md)
{
MQTTMessage* m = md->message;
// Check if "url" is included in the message payload
if(strstr(m->payload, "url") != NULL)
{
char* strPtr = NULL;
char download_url[256] = {0};
// Empty the download_url array
memset(download_url,0x0,sizeof(download_url));
// Find the location of "url"
strPtr = strstr(m->payload, "url");
strPtr = strPtr + 6;
// Starting with strPtr, will read the string until the next double quotes and save it to download_url
sscanf(strPtr,"%[^\"]",download_url);
slog(MISC_PRINT, SLOG_DEBUG, "download_url %s\n",download_url);
//printf("download_url %s\n",download_url);
if(download_url[0] != '\0')
{
//printf("start fota download\n");
slog(MISC_PRINT, SLOG_DEBUG, "start fota download\n");
//Do the FOTA download
dmp_fota_download(download_url);
sleep(10);
//Do the FOTA upgrade
dmp_fota_callback(LYNQ_FOTA_DOWNLOADEND, 0);
}
}
}
/**
* @brief Download the FOTA pack
*
* Download the FOTA package from the given URL and save it to the specified path。
*
* @param url package download address
*
* @return If the return value is 0, the download succeeds. If the return value is 0, the download fails
*/
void dmp_fota_download(char* url)
{
int ret = -1;
//printf("start fota download\n");
slog(MISC_PRINT, SLOG_DEBUG, "start fota download\n");
CURL *curl = curl_easy_init();
FILE *fp = fopen("/cache/zte_fota/delta.package", "wb");
if (fp == NULL)
{
// If the directory does not exist, create a directory
ret = mkdir("/cache/zte_fota",0777);
if(ret == -1) {
perror("mkdir");
return -1;
}
// Try opening the file again
fp = fopen("/cache/zte_fota/delta.package", "wb");
if (fp == NULL)
{
perror("open file error\n");
return -1;
}
}
if (curl && fp)
{
// Set the CURL option to specify the download URL
curl_easy_setopt(curl, CURLOPT_URL, url);
// Set the CURL option to specify a pointer to the file to write to
curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);
// Set the CURL option to disable SSL certificate authentication
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYPEER,0L);
// 设置CURL选项,不验证SSL主机名
curl_easy_setopt(curl,CURLOPT_SSL_VERIFYHOST,0L);
// Set the CURL option to not validate the SSL host name
CURLcode res = curl_easy_perform(curl);
if (res != CURLE_OK)
{
//printf("curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
slog(MISC_PRINT, SLOG_DEBUG, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
}
else
{
slog(MISC_PRINT, SLOG_DEBUG, "downloaded file successfully\n");
//printf("downloaded file successfully\n");
}
fclose(fp);
}
else
{
slog(MISC_PRINT, SLOG_DEBUG, "curl_easy_init() failed\n");
//printf("curl_easy_init() failed\n");
}
// Clear the CURL object
curl_easy_cleanup(curl);
// Clear CURL global resources
curl_global_cleanup();
return 0;
}
/**
* @brief DMP FOTA 回调函数
*
*/
void dmp_fota_callback(lynq_fota_status status, int percent)
{
MQTTMessage pubmsg2;
char deviceKey[100] = {0};
char ota_progress_topic[100] = {0};
char payload_progress[512] = {0};
int ret = 0;
pubmsg2.qos = QOS0;
pubmsg2.retained = 0;
pubmsg2.dup = 0;
memset(deviceKey, 0x0, sizeof(deviceKey));
memset(ota_progress_topic, 0x0, sizeof(ota_progress_topic));
get_cfg_item("imei", deviceKey);
sprintf(ota_progress_topic,"$sys/%s/%s/ota/progress", productKey, deviceKey);
//start verify
system("fota_upi -u verify");
FILE *update_status_fp;
char update_status[10] = {0};
//start to read updata_status
update_status_fp = fopen("/cache/zte_fota/update_status", "r");
if (update_status_fp != NULL)
{
ret = fread(update_status, 10, 1, update_status_fp);
slog(MISC_PRINT, SLOG_DEBUG, "update_status %s\n", update_status);
//printf("update_status %s\n", update_status);
fclose(update_status_fp);
}
else
{
slog(MISC_PRINT, SLOG_DEBUG, "open update_status failed\n");
//printf("open update_status failed\n");
return -1;
}
//if update_status is 1, means package mismatch
if(strcmp(update_status, "1") == 0)
{
sprintf(payload_progress,"{\"messageId\":\"%d\",\"params\": {\"step\":\"%d\",\"desc\": \"%d\",\"otaType\": \"%s\"}}",message_id,-3,0,"default");
message_id ++;
pubmsg2.payload = (void*)payload_progress;
pubmsg2.payloadlen = strlen((char*)pubmsg2.payload);
ret = MQTTPublish(&dmp_MqttClient, ota_progress_topic, &pubmsg2);
slog(MISC_PRINT, SLOG_DEBUG, "pub result:PACKAGE_MISMATCH ret = %d\n", ret);
//printf("pub result:PACKAGE_MISMATCH ret = %d\n", ret);
}
//else if update_status is 0, means package match, start upgrade
else if (strcmp(update_status, "0") == 0)
{
while(percent <= 100)
{
sprintf(payload_progress,"{\"messageId\":\"%d\",\"params\": {\"step\":\"%d\",\"desc\": \"%d\",\"otaType\": \"%s\"}}",message_id,0,percent,"default");
message_id ++;
pubmsg2.payload = (void*)payload_progress;
pubmsg2.payloadlen = strlen((char*)pubmsg2.payload);
ret = MQTTPublish(&dmp_MqttClient, ota_progress_topic, &pubmsg2);
slog(MISC_PRINT, SLOG_DEBUG, "publish result ret = %d\n", ret);
//printf("publish result ret = %d\n", ret);
percent+=10;
sleep(1);
}
system("fota_upi -u recovery");
}
}
/**
* @brief Reconnect to the MQTT client
*
* Try to reconnect to the MQTT client by re-establishing the network connection and connecting to the MQTT client.
*
* @return Connection status code, 0 is returned on success, negative value is returned on failure
*/
int MqttClientReconnect()
{
int rc = 0;
// Disconnect from the network
NetworkDisconnect(&dmp_MqttNetwork);
// Select a connection mode based on the port number
if(DMP_PORT == 8883)
{
rc = NetworkConnectBySSL(&dmp_MqttNetwork, DMP_HOST, DMP_PORT, "");
}
else if(DMP_PORT == 1883)
{
rc = NetworkConnect(&dmp_MqttNetwork, DMP_HOST, DMP_PORT);
}
if (rc < 0)
{
slog(MISC_PRINT, SLOG_DEBUG, "mqtt connect failed,rc:%d\n");
//printf("mqtt connect failed,rc:%d\n");
return -2;
}
// Reconnect to the MQTT server
rc = MQTTConnect(&dmp_MqttClient, &connectData2);
if (rc != 0)
{
if(rc > 0 && rc <= 5)
{
slog(MISC_PRINT, SLOG_DEBUG, "MQTTConnect failed,rc:%d, %s\n", rc,connackReturnCodeStr[rc]);
//printf("MQTTConnect failed,rc:%d, %s\n", rc,connackReturnCodeStr[rc]);
}
else
{
slog(MISC_PRINT, SLOG_DEBUG, "MQTTConnect failed,rc:%d\n", rc);
//printf("MQTTConnect failed,rc:%d\n", rc);
}
return -3;
}
return rc;
}
/**
* @brief
*
*
*/
void yield_thread(void)
{
int ret;
int repo_count = 0;
int retry_count = 0;
int nextReconnTime = 0;
int reconnCount = 0;
while(!toStop)
{
// Check whether the data reporting time is reached
if (repo_count >= (dmp_repo_time/30))
{
mbtk_dmp_repo_msg();
repo_count = 0;
continue;
}
// Perform the yield operation on MQTT to listen for messages
ret = MQTTYield(&dmp_MqttClient, 1000);
slog(MISC_PRINT, SLOG_DEBUG, "yield ret = %d,mqttclientisconnected = %d\n",ret,MQTTIsConnected(&dmp_MqttClient));
//printf("yield ret = %d,mqttclientisconnected = %d\n",ret,MQTTIsConnected(&dmp_MqttClient));
sleep(30);
// If the yield operation does not return 0, the number of retries is increased
if (ret != 0)
{
retry_count++;
}
// If the number of retries exceeds 10, retry
if(retry_count > 10)
{
reconnCount++;
// Calculate the next reconnection time based on the number of reconnections
if(reconnCount < MQTT_RECONN_MAXCOUNT)
{
nextReconnTime = (1 << (reconnCount/5))*MQTT_RECONN_MINTIMESPACE;
}
else
{
nextReconnTime = (1 << (MQTT_RECONN_MAXCOUNT/5))*MQTT_RECONN_MINTIMESPACE;
}
slog(MISC_PRINT, SLOG_DEBUG, "retry_count = %d,need to reconnect\n", retry_count);
//printf("retry_count = %d,need to reconnect\n", retry_count);
// Try to reconnect
ret = MqttClientReconnect(1000);
if (ret != 0)
{
slog(MISC_PRINT, SLOG_DEBUG, "MQTT reconnect failed,rc:%d\n", ret);
//printf("MQTT reconnect failed,rc:%d\n", ret);
ret = -101;
usleep(nextReconnTime);
}
else
{
slog(MISC_PRINT, SLOG_DEBUG, "MQTT reconnect success\n");
//printf("MQTT reconnect success\n");
//resubscribe topic
mbtk_subscribe_topic();
reconnCount = 0;
ret = 1;
}
retry_count = 0;
continue;
}
repo_count++;
usleep(1000*100);
}
}
void utils_hmac_sha256(const uint8_t *source, uint32_t sour_len, const uint8_t *key, uint32_t key_len, uint8_t out[32])
{
uni_sha256_s text;
uint8_t k_itext[UNI_SHA256_KEY_SIZE];
uint8_t k_otext[UNI_SHA256_KEY_SIZE];
int32_t i;
if((NULL == source) || (NULL == key) || (NULL == out))
{
//printf("source or key or out is NULL\n");
slog(MISC_PRINT, SLOG_DEBUG, "source or key or out is NULL\n");
return;
}
if(key_len > UNI_SHA256_KEY_SIZE)
{
slog(MISC_PRINT, SLOG_DEBUG, "length:%d is not enough\n", key_len);
//printf("length:%d is not enough\n", key_len);
return;
}
memset(k_itext, 0, sizeof(k_itext));
memset(k_otext, 0, sizeof(k_otext));
memcpy(k_itext, key, key_len);
memcpy(k_otext, key, key_len);
for(i = 0; i < UNI_SHA256_KEY_SIZE; i++)
{
k_itext[i] ^= 0x36;
k_otext[i] ^= 0x5c;
}
utils_sha256_init(&text);
utils_sha256_starts(&text);
utils_sha256_update(&text, k_itext, UNI_SHA256_KEY_SIZE);
utils_sha256_update(&text, source, sour_len);
utils_sha256_finish(&text, out);
utils_sha256_init(&text);
utils_sha256_starts(&text);
utils_sha256_update(&text, k_otext, UNI_SHA256_KEY_SIZE);
utils_sha256_update(&text, out, UNI_SHA256_TARGET_SIZE);
utils_sha256_finish(&text, out);
}
void cfinish(int sig)
{
signal(SIGINT, NULL);
toStop = 1;
}
/**
* @brief The callback function when the message arrives
*
* This callback function is triggered when an MQTT message is received.
*
* @param md Message data pointer
*/
void messageArrived(MessageData* md)
{
//printf("messageArrived\n");
slog(MISC_PRINT, SLOG_DEBUG, "messageArrived\n");
arrived_flag = 1;
MQTTMessage* message = md->message;
//printf("%.*s\t", md->topicName->lenstring.len, md->topicName->lenstring.data);
//printf("%.*s\n", (int)message->payloadlen, (char*)message->payload);
slog(MISC_PRINT, SLOG_DEBUG, "%.*s\t", md->topicName->lenstring.len, md->topicName->lenstring.data);
slog(MISC_PRINT, SLOG_DEBUG, "%.*s\n", (int)message->payloadlen, (char*)message->payload);
}
/**
* @brief Process MQTT topic messages that auto registration
* @param md Message data pointer
*/
void _mqtt_noreg_topic_handle(MessageData *md)
{
cJSON *root = NULL;
cJSON *pItem = NULL;
MQTTMessage* message = md->message;
//printf("%.*s\t", md->topicName->lenstring.len, md->topicName->lenstring.data);
//printf("%.*s\n", (int)message->payloadlen, (char*)message->payload);
slog(MISC_PRINT, SLOG_DEBUG, "%.*s\t", md->topicName->lenstring.len, md->topicName->lenstring.data);
slog(MISC_PRINT, SLOG_DEBUG, "%.*s\n", (int)message->payloadlen, (char*)message->payload);
// If the topic name does not contain "/ext/autoregist", a prompt is printed and returned
if(strstr(md->topicName->lenstring.data, "/ext/autoregist") == NULL)
{
//printf("the packet is not /ext/autoregist");
slog(MISC_PRINT, SLOG_DEBUG, "the packet is not /ext/autoregist");
return;
}
root = cJSON_Parse(message->payload);
if(NULL == root)
{
slog(MISC_PRINT, SLOG_DEBUG, "cJSON_Parse error:[%s]", cJSON_GetErrorPtr());
//printf("cJSON_Parse error:[%s]", cJSON_GetErrorPtr());
return;
}
pItem = cJSON_GetObjectItem(root, "params");
if(NULL != pItem)
{
pItem = cJSON_GetObjectItem(pItem, "token");
if(NULL != pItem)
{
strncpy(g_TokenStr, pItem->valuestring, sizeof(g_TokenStr)-1);
}
}
//printf("get token %s\n", g_TokenStr);
slog(MISC_PRINT, SLOG_DEBUG, "get token %s\n", g_TokenStr);
if(root != NULL)
{
cJSON_Delete(root);
}
}
/**
* @brief acquisition of signal quality
*
* Gets the values of signal quality, RSSI, RSRP, and RSRQ from the nv and assigns them to the specified variable.
*
* @param csq
* @param rssi
* @param rsrp
* @param rsrq
*
* @return
*/
int appGetSignalQualitySync(uint8_t *csq, int8_t *rssi, int8_t *rsrp, int8_t *rsrq)
{
char value_temp[10] = {0};
//printf("get csq \n");
slog(MISC_PRINT, SLOG_DEBUG, "get csq \n");
get_cfg_item("csq", value_temp);
if (strlen(value_temp) > 0)
{
*csq = atoi(value_temp);
}
else
{
*csq = 0;
}
bzero(value_temp, sizeof(value_temp));
//printf("get rssi \n");
slog(MISC_PRINT, SLOG_DEBUG, "get rssi \n");
get_cfg_item("rssi", value_temp);
if (strlen(value_temp) > 0)
{
*rssi = atoi(value_temp);
}
else
{
*rssi = 0;
}
bzero(value_temp, sizeof(value_temp));
slog(MISC_PRINT, SLOG_DEBUG, "get rsrp \n");
//printf("get rsrp \n");
get_cfg_item("lte_rsrp", value_temp);
if (strlen(value_temp) > 0)
{
*rsrp = atoi(value_temp);
}
else
{
*rsrp = 0;
}
bzero(value_temp, sizeof(value_temp));
return 0;
}
/**
* @brief Gets network load information and returns it in JSON format
*
* The obtained network load information is converted into JSON format and stored in the incoming character array.
*
* @param net_payload A character array that stores network load information in JSON format
*
* @return 0 indicates success and -1 indicates failure
*/
int mbtk_get_net_payload(char * net_payload)
{
char *cjson_str = NULL;
cJSON *jsonroot = NULL;
int ret = 0;
time_t time_test = 0;
char time_current[100] = {0};
cJSON * ObjArr = NULL;
//ol_cid_info_struct info;
uint8_t csq = 0;
int8_t snr = 0;
int8_t rsrp = 0;
int8_t rsrq = 0;
int8_t sRsrq = 0;
int8_t rssi = 0;
//BasicCellListInfo cellinfo;
char str[10] = {0};
char cellid[10] = {0};
char pci[10] = {0};
time_test = time(NULL);
//printf("ol_time = %d\n",time_test);
slog(MISC_PRINT, SLOG_DEBUG, "ol_time = %d\n",time_test);
sprintf(time_current,"%u000",time_test);
jsonroot = cJSON_CreateObject();
if(NULL == jsonroot)
{
//printf("cjson ob error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson ob error\n");
return -1;
}
cJSON_AddStringToObject(jsonroot, "messageId", "11");
ObjArr = cJSON_CreateArray();
//printf("wan_ipaddr\n");
slog(MISC_PRINT, SLOG_DEBUG, "wan_ipaddr\n");
char wan_ip[128] = {0};
get_cfg_item("wan_ipaddr",wan_ip);
cJSON * Obj_ip = NULL;
Obj_ip = cJSON_CreateObject();
if(NULL == Obj_ip)
{
//printf("create cjson Obj_ip error\n");
slog(MISC_PRINT, SLOG_DEBUG, "create cjson Obj_ip error\n");
return -1;
}
cJSON_AddStringToObject(Obj_ip, "key", "WANIP");
cJSON_AddStringToObject(Obj_ip, "value", wan_ip);
cJSON_AddStringToObject(Obj_ip, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_ip);
ret = appGetSignalQualitySync(&csq, &rssi, &rsrp, &rsrq);
//printf("csq %d rssi%d rsrp %d \n",csq,rssi,rsrp);
slog(MISC_PRINT, SLOG_DEBUG, "csq %d rssi%d rsrp %d \n",csq,rssi,rsrp);
if(ret == 0)
{
memset(str,0x0,10);
sprintf(str,"%d",csq);
if(str[0] != '\0')
{
cJSON * Objcsq = NULL;
Objcsq = cJSON_CreateObject();
if(NULL == Objcsq)
{
//printf("cjson Objcsq error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Objcsq error\n");
return -1;
}
cJSON_AddStringToObject(Objcsq, "key", "csq");
cJSON_AddStringToObject(Objcsq, "value", str);
cJSON_AddStringToObject(Objcsq, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Objcsq);
}
memset(str,0x0,10);
sprintf(str,"%d",rsrp);
if(str[0] != '\0')
{
cJSON * Objrsrp = NULL;
Objrsrp = cJSON_CreateObject();
if(NULL == Objrsrp)
{
//printf("cjson Objrsrp error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Objrsrp error\n");
return -1;
}
cJSON_AddStringToObject(Objrsrp, "key", "RSRP");
cJSON_AddStringToObject(Objrsrp, "value", str);
cJSON_AddStringToObject(Objrsrp, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Objrsrp);
}
/*
memset(str,0,10);
if (rsrq != 127)
{
if (rsrq <= 0)
{
sRsrq = (rsrq - 39) >> 1;
}
else if (rsrq <= 34)
{
sRsrq = (rsrq - 40) >> 1;
}
else
{
sRsrq = (rsrq - 41) >> 1;
}
}
itoa(sRsrq, str, 10);
OL_LOG_PRINTF("str %s",str);
if(str[0] != '\0')
{
cJSON * Objrsrq = NULL;
Objrsrq = cJSON_CreateObject();
if(NULL == Objrsrq)
{
OL_LOG_PRINTF("cjson Objrsrp error");
return -1;
}
cJSON_AddStringToObject(Objrsrq, "key", "RSRQ");
cJSON_AddStringToObject(Objrsrq, "value", str);
cJSON_AddStringToObject(Objrsrq, "ts", time);
cJSON_AddItemToArray(ObjArr, Objrsrq);
}
*/
memset(str,0x0,10);
sprintf(str,"%d",rssi);
if(str[0] != '\0')
{
cJSON * Objrssi = NULL;
Objrssi = cJSON_CreateObject();
if(NULL == Objrssi)
{
//printf("cjson Objrssi error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Objrssi error\n");
return -1;
}
cJSON_AddStringToObject(Objrssi, "key", "RSSI");
cJSON_AddStringToObject(Objrssi, "value", str);
cJSON_AddStringToObject(Objrssi, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Objrssi);
}
}
//printf("get cellid \n");
slog(MISC_PRINT, SLOG_DEBUG, "get cellid \n");
get_cfg_item("cell_id", cellid);
if (strlen(cellid) == 0)
{
sprintf(cellid,"%d",0);
}
//printf("get pci \n");
slog(MISC_PRINT, SLOG_DEBUG, "get pci \n");
get_cfg_item("lte_pci", pci);
if (strlen(pci) == 0)
{
sprintf(pci,"%d",0);
}
cJSON * ObjCID = NULL;
ObjCID = cJSON_CreateObject();
if(NULL == ObjCID)
{
//printf("cjson ObjCID error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson ObjCID error\n");
return -1;
}
cJSON_AddStringToObject(ObjCID, "key", "cellID");
cJSON_AddStringToObject(ObjCID, "value", cellid);
cJSON_AddStringToObject(ObjCID, "ts", time_current);
cJSON_AddItemToArray(ObjArr, ObjCID);
//printf("pci %s\n", pci);
slog(MISC_PRINT, SLOG_DEBUG, "pci %s\n", pci);
cJSON * ObjPID = NULL;
ObjPID = cJSON_CreateObject();
if(NULL == ObjPID)
{
//printf("cjson ObjCID error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson ObjCID error\n");
return -1;
}
cJSON_AddStringToObject(ObjPID, "key", "PCI");
cJSON_AddStringToObject(ObjPID, "value", pci);
cJSON_AddStringToObject(ObjPID, "ts", time_current);
cJSON_AddItemToArray(ObjArr, ObjPID);
cJSON * Objson = NULL;
Objson = cJSON_CreateObject();
cJSON_AddItemToObject(Objson, "data", ObjArr);
cJSON_AddItemToObject(jsonroot, "params", Objson);
cjson_str = cJSON_Print(jsonroot);
//printf("json root %s\n",cjson_str);
slog(MISC_PRINT, SLOG_DEBUG, "json root %s\n",cjson_str);
strcpy(net_payload, cjson_str);
free(cjson_str);
return 0;
}
void mbtk_pub_sim_payload(char * key,char *value)
{
char payload_temp[512] = {0};
char pub_topic[100] = {0};
char deviceKey[100] = {0};
MQTTMessage pubmsg;
MQTTMessage pubmsg2;
int ret = 0;
time_t time_test = 0;
char time_cur[100] = {0};
memset(deviceKey, 0x0, sizeof(deviceKey));
get_cfg_item("imei",deviceKey);
memset(pub_topic, 0x0, sizeof(pub_topic));
memset(payload_temp, 0x0, sizeof(payload_temp));
time_test = time(NULL);
//printf("time_test %d\n", time_test);
slog(MISC_PRINT, SLOG_DEBUG, "time_test %d\n", time_test);
sprintf(time_cur, "%u000", time_test);
if(sim_type_flag)
{
sim_type_flag = 0;
int value_temp = 0;
value_temp = atoi(value);
//printf("value_temp %d\n",value_temp);
slog(MISC_PRINT, SLOG_DEBUG, "value_temp %d\n",value_temp);
sprintf(payload_temp,"{\"messageId\":\"%d\",\"params\": {\"key\":\"%s\",\"value\": \"%d\",\"ts\":\"%s\"}}",message_id,key,value_temp,time_cur);
}
else
{
sprintf(payload_temp,"{\"messageId\":\"%d\",\"params\": {\"key\":\"%s\",\"value\": \"%s\",\"ts\":\"%s\"}}",message_id,key,value,time_cur);
}
//printf("payload_temp %s\n", payload_temp);
slog(MISC_PRINT, SLOG_DEBUG, "payload_temp %s\n", payload_temp);
message_id++;
pubmsg.payload = (void*)payload_temp;
pubmsg.payloadlen = strlen((char*)pubmsg.payload);
pubmsg.qos = QOS0;
pubmsg.retained = 0;
pubmsg.dup = 0;
sprintf(pub_topic,"$sys/%s/%s/property/pub", productKey, deviceKey);
//printf("pub_topic %s\n", pub_topic);
slog(MISC_PRINT, SLOG_DEBUG, "pub_topic %s\n", pub_topic);
ret = MQTTPublish(&dmp_MqttClient, pub_topic, &pubmsg);
if (ret != 0)
{
//printf("MQTT_Publish failed,ret %d\n", ret);
slog(MISC_PRINT, SLOG_DEBUG, "MQTT_Publish failed,ret %d\n", ret);
}
else
{
//printf("MQTT_Publish success\n");
slog(MISC_PRINT, SLOG_DEBUG, "MQTT_Publish success\n");
}
usleep(500*1000);
}
int mbtk_cjson_test(char * cjson_data)
{
char *cjson_str = NULL;
cJSON *jsonroot = NULL;
int ret = 0;
char sn[40] = {0};
char imei[32] = {0};
time_t time_test = 0;
char time_cur[50] = {0};
cJSON * ObjArr = NULL;
time_test = time(NULL);
//printf("ol_time = %d\n",time_test);
slog(MISC_PRINT, SLOG_DEBUG, "ol_time = %d\n",time_test);
sprintf(time_cur,"%u000",time_test);
jsonroot = cJSON_CreateObject();
if(NULL == jsonroot)
{
//printf("cjson ob error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson ob error\n");
return -1;
}
cJSON_AddStringToObject(jsonroot, "messageId", "10");
ObjArr = cJSON_CreateArray();
if(strlen(dmp_repo_config.DeviceManu) > 0)
{
cJSON * ObjFirst = NULL;
ObjFirst = cJSON_CreateObject();
if(NULL == ObjFirst)
{
//printf("create cjson ObjFirst error\n");
slog(MISC_PRINT, SLOG_DEBUG, "create cjson ObjFirst error\n");
return -1;
}
cJSON_AddStringToObject(ObjFirst, "key", "DeviceManu");
cJSON_AddStringToObject(ObjFirst, "value", dmp_repo_config.DeviceManu);
cJSON_AddStringToObject(ObjFirst, "ts", time_cur);
cJSON_AddItemToArray(ObjArr, ObjFirst);
}
if(strlen(dmp_repo_config.DeviceType) > 0)
{
cJSON * Obj2 = NULL;
Obj2 = cJSON_CreateObject();
if(NULL == Obj2)
{
//printf("create cjson Obj2 error\n");
slog(MISC_PRINT, SLOG_DEBUG, "create cjson Obj2 error\n");
return -1;
}
cJSON_AddStringToObject(Obj2, "key", "DeviceType");
cJSON_AddStringToObject(Obj2, "value", dmp_repo_config.DeviceType);
cJSON_AddStringToObject(Obj2, "ts", time_cur);
cJSON_AddItemToArray(ObjArr, Obj2);
}
memset(sn, 0x0, sizeof(sn));
ret = get_cfg_item("SERIAL_TSP",sn);
if(ret == 1 && sn[0] != '\0')
{
cJSON * Obj_sn = NULL;
Obj_sn = cJSON_CreateObject();
if(NULL == Obj_sn)
{
//printf("cjson Obj_sn error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_sn error\n");
return -1;
}
cJSON_AddStringToObject(Obj_sn, "key", "sn");
cJSON_AddStringToObject(Obj_sn, "value", sn);
cJSON_AddStringToObject(Obj_sn, "ts", time_cur);
cJSON_AddItemToArray(ObjArr, Obj_sn);
}
memset(imei, 0x0, sizeof(imei));
ret = get_cfg_item("imei",imei);
if(ret == 1 && imei[0] != '\0')
{
cJSON * Obj_imei = NULL;
Obj_imei = cJSON_CreateObject();
if(NULL == Obj_imei)
{
//printf("cjson Obj_imei error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_imei error\n");
return -1;
}
cJSON_AddStringToObject(Obj_imei, "key", "moduleIMEI");
cJSON_AddStringToObject(Obj_imei, "value", imei);
cJSON_AddStringToObject(Obj_imei, "ts", time_cur);
cJSON_AddItemToArray(ObjArr, Obj_imei);
}
cJSON * Obj_MANU = NULL;
Obj_MANU = cJSON_CreateObject();
if(NULL == Obj_MANU)
{
//printf("cjson Obj_MANU error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_MANU error\n");
return -1;
}
cJSON_AddStringToObject(Obj_MANU, "key", "manufacturer");
cJSON_AddStringToObject(Obj_MANU, "value", "Mobiletek");
cJSON_AddStringToObject(Obj_MANU, "ts", time_cur);
cJSON_AddItemToArray(ObjArr, Obj_MANU);
cJSON * Obj_mtype = NULL;
Obj_mtype = cJSON_CreateObject();
if(NULL == Obj_mtype)
{
//printf("cjson Obj_mtype error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_mtype error\n");
return -1;
}
cJSON_AddStringToObject(Obj_mtype, "key", "moduleType");
cJSON_AddStringToObject(Obj_mtype, "value", (char *)"R305");
cJSON_AddStringToObject(Obj_mtype, "ts", time_cur);
cJSON_AddItemToArray(ObjArr, Obj_mtype);
cJSON * Obj_cmanu = NULL;
Obj_cmanu = cJSON_CreateObject();
if(NULL == Obj_cmanu)
{
//printf("cjson Obj_cmanu error");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_cmanu error");
return -1;
}
cJSON_AddStringToObject(Obj_cmanu, "key", "chipManufacturer");
cJSON_AddStringToObject(Obj_cmanu, "value", "ZTE");
cJSON_AddStringToObject(Obj_cmanu, "ts", time_cur);
cJSON * Obj_ctype = NULL;
Obj_ctype = cJSON_CreateObject();
if(NULL == Obj_ctype)
{
//printf("cjson Obj_ctype error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_ctype error\n");
return -1;
}
cJSON_AddStringToObject(Obj_ctype, "key", "chipType");
cJSON_AddStringToObject(Obj_ctype, "value", "ZTE7520V3");
cJSON_AddStringToObject(Obj_ctype, "ts", time_cur);
cJSON * Obj_sver = NULL;
Obj_sver = cJSON_CreateObject();
if(NULL == Obj_sver)
{
//printf("cjson Obj_sver error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_sver error\n");
return -1;
}
char version[32] = {0};
get_cfg_item("cr_version",version);
cJSON_AddStringToObject(Obj_sver, "key", "SoftVersion");
cJSON_AddStringToObject(Obj_sver, "value", version);
cJSON_AddStringToObject(Obj_sver, "ts", time_cur);
cJSON_AddItemToArray(ObjArr, Obj_cmanu);
cJSON_AddItemToArray(ObjArr, Obj_ctype);
cJSON_AddItemToArray(ObjArr, Obj_sver);
cJSON * Objson = NULL;
Objson = cJSON_CreateObject();
cJSON_AddItemToObject(Objson, "data", ObjArr);
cJSON_AddItemToObject(jsonroot, "params", Objson);
cjson_str = cJSON_Print(jsonroot);
//printf("json root %s\n",cjson_str);
slog(MISC_PRINT, SLOG_DEBUG, "json root %s\n",cjson_str);
strcpy(cjson_data, cjson_str);
free(cjson_str);
return 0;
}
/**
* @brief Gets wifi load information and returns it in JSON format
*
* The obtained wifi load information is converted into JSON format and stored in the incoming character array.
*
* @param wifi_payload A character array that stores wifi load information in JSON format
*
* @return 0 indicates success and -1 indicates failure
*/
int mbtk_get_wifi_payload(char * wifi_payload)
{
char *cjson_str = NULL;
cJSON *jsonroot = NULL;
int ret = 0;
time_t time_test = 0;
char time_current[100] = {0};
cJSON *ObjArr = NULL;
//WIFI information
char wifi_mac[32] = {0};
char lan_ipaddr[32] = {0};
char wifiEnabled[10] = {0};
char wifi_ssid[32] = {0};
char authmode[10] = {0};
char wifi_pwd[32] = {0};
char max_connt[32] = {0};
char wifi_list[1024] = {0};
time_test = time(NULL);
//printf("time_test %d\n", time_test);
slog(MISC_PRINT, SLOG_DEBUG, "time_test %d\n", time_test);
sprintf(time_current,"%u000",time_test);
jsonroot = cJSON_CreateObject();
if(NULL == jsonroot)
{
//printf("cjson root error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson root error\n");
return -1;
}
cJSON_AddStringToObject(jsonroot, "messageId", "12");
ObjArr = cJSON_CreateArray();
//printf("wifiEnabled\n");
slog(MISC_PRINT, SLOG_DEBUG, "wifiEnabled\n");
get_cfg_item("wifiEnabled", wifiEnabled);
cJSON * Obj_wifiEnabled = NULL;
Obj_wifiEnabled = cJSON_CreateObject();
if(NULL == Obj_wifiEnabled)
{
//printf("cjson Obj_wifiEnabled error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_wifiEnabled error\n");
return -1;
}
//printf("wifiEnabled %s\n", wifiEnabled);
slog(MISC_PRINT, SLOG_DEBUG, "wifiEnabled %s\n", wifiEnabled);
int wifi_enable = atoi(wifiEnabled);
if (wifi_enable == 1)
{
sprintf(wifiEnabled,"true");
}
else
{
sprintf(wifiEnabled,"false");
}
cJSON_AddStringToObject(Obj_wifiEnabled, "key", "WifiEnable");
cJSON_AddStringToObject(Obj_wifiEnabled, "value", wifiEnabled);
cJSON_AddStringToObject(Obj_wifiEnabled, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_wifiEnabled);
if(wifi_enable == 1)
{
//printf("wifi_list\n");
slog(MISC_PRINT, SLOG_DEBUG, "wifi_list\n");
lynq_wlan_get_station_list(wifi_list);
//printf("wifi_list %s\n", wifi_list);
slog(MISC_PRINT, SLOG_DEBUG, "wifi_list %s\n", wifi_list);
if(wifi_list[0] != '\0')
{
cJSON * Obj_wifi_list = NULL;
Obj_wifi_list = cJSON_CreateObject();
if(NULL == Obj_wifi_list)
{
//printf("cjson Obj_wifi_list error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_wifi_list error\n");
return -1;
}
cJSON_AddStringToObject(Obj_wifi_list, "key", "DeviceList");
cJSON_AddStringToObject(Obj_wifi_list, "value", wifi_list);
cJSON_AddStringToObject(Obj_wifi_list, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_wifi_list);
}
//printf("wifi_mac\n");
slog(MISC_PRINT, SLOG_DEBUG, "wifi_mac\n");
get_cfg_item("wifi_mac", wifi_mac);
cJSON * Obj_mac = NULL;
Obj_mac = cJSON_CreateObject();
if(NULL == Obj_mac)
{
//printf("cjson Obj_mac error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_mac error\n");
return -1;
}
cJSON_AddStringToObject(Obj_mac, "key", "MAC");
cJSON_AddStringToObject(Obj_mac, "value", wifi_mac);
cJSON_AddStringToObject(Obj_mac, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_mac);
//printf("lan_ipaddr\n");
slog(MISC_PRINT, SLOG_DEBUG, "lan_ipaddr\n");
get_cfg_item("lan_ipaddr", lan_ipaddr);
cJSON * Obj_gateway = NULL;
Obj_gateway = cJSON_CreateObject();
if(NULL == Obj_gateway)
{
//printf("cjson Obj_gateway error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_gateway error\n");
return -1;
}
cJSON_AddStringToObject(Obj_gateway, "key", "GatewayIP");
cJSON_AddStringToObject(Obj_gateway, "value", lan_ipaddr);
cJSON_AddStringToObject(Obj_gateway, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_gateway);
//printf("wifi_ssid\n");
slog(MISC_PRINT, SLOG_DEBUG, "wifi_ssid\n");
get_cfg_item("SSID1", wifi_ssid);
cJSON * Obj_ssid = NULL;
Obj_ssid = cJSON_CreateObject();
if(NULL == Obj_ssid)
{
//printf("cjson Obj_ssid error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_ssid error\n");
return -1;
}
cJSON_AddStringToObject(Obj_ssid, "key", "WifiSSID");
cJSON_AddStringToObject(Obj_ssid, "value", wifi_ssid);
cJSON_AddStringToObject(Obj_ssid, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_ssid);
//printf("authmode\n");
slog(MISC_PRINT, SLOG_DEBUG, "authmode\n");
get_cfg_item("AuthMode", authmode);
cJSON * Obj_authmode = NULL;
Obj_authmode = cJSON_CreateObject();
if(NULL == Obj_authmode)
{
//printf("cjson Obj_authmode error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_authmode error\n");
return -1;
}
cJSON_AddStringToObject(Obj_authmode, "key", "WifiAuth");
cJSON_AddStringToObject(Obj_authmode, "value", authmode);
cJSON_AddStringToObject(Obj_authmode, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_authmode);
//printf("wifi_pwd\n");
slog(MISC_PRINT, SLOG_DEBUG, "wifi_pwd\n");
get_cfg_item("WPAPSK1", wifi_pwd);
cJSON * Obj_pwd = NULL;
Obj_pwd = cJSON_CreateObject();
if(NULL == Obj_pwd)
{
//printf("cjson Obj_pwd error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_pwd error\n");
return -1;
}
cJSON_AddStringToObject(Obj_pwd, "key", "WifiPwd");
cJSON_AddStringToObject(Obj_pwd, "value", wifi_pwd);
cJSON_AddStringToObject(Obj_pwd, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_pwd);
//printf("max_connt\n");
slog(MISC_PRINT, SLOG_DEBUG, "max_connt\n");
get_cfg_item("MAX_Access_num", max_connt);
if (strlen(max_connt) == 0)
{
sprintf(max_connt,"0");
}
cJSON * Obj_max_connt = NULL;
Obj_max_connt = cJSON_CreateObject();
if(NULL == Obj_max_connt)
{
//printf("cjson Obj_max_connt error\n");
slog(MISC_PRINT, SLOG_DEBUG, "cjson Obj_max_connt error\n");
return -1;
}
cJSON_AddStringToObject(Obj_max_connt, "key", "MaxConn");
cJSON_AddStringToObject(Obj_max_connt, "value", max_connt);
cJSON_AddStringToObject(Obj_max_connt, "ts", time_current);
cJSON_AddItemToArray(ObjArr, Obj_max_connt);
}
cJSON * Objson = NULL;
Objson = cJSON_CreateObject();
cJSON_AddItemToObject(Objson, "data", ObjArr);
cJSON_AddItemToObject(jsonroot, "params", Objson);
cjson_str = cJSON_Print(jsonroot);
//printf("cjson_str %s\n", cjson_str);
slog(MISC_PRINT, SLOG_DEBUG, "cjson_str %s\n", cjson_str);
strcpy(wifi_payload,cjson_str);
free(cjson_str);
return 0;
}
/**
* @brief Publish messages to the MQTT server
*
* This function is responsible for publishing the message to the MQTT server. Depending on the module (sim, network, wifi),
* The corresponding message payload is generated and published to the specified topic via the MQTT protocol.
*
* @note Before publishing a message, the MQTT client's ping response is checked to see if it is suspended, and if it is suspended, it is not published.
*/
void mbtk_dmp_repo_msg(void)
{
char payload[2048] = {0};
char pub_topic[100] = {0};
//sim
MQTTMessage pubmsg;
//network
MQTTMessage pubmsg2;
//wifi
MQTTMessage pubmsg3;
int ret = 0;
char deviceKey[32] = {0};
memset(pub_topic, 0x0, sizeof(pub_topic));
memset(payload, 0x0, sizeof(payload));
memset(deviceKey, 0x0, sizeof(deviceKey));
get_cfg_item("imei",deviceKey);
//json test
mbtk_cjson_test(payload);
if (dmp_MqttClient.ping_outstanding == 0)
{
pubmsg.payload = (void*)payload;
pubmsg.payloadlen = strlen((char*)pubmsg.payload);
pubmsg.qos = QOS0;
pubmsg.retained = 0;
pubmsg.dup = 0;
sprintf(pub_topic,"$sys/%s/%s/property/batch", productKey, deviceKey);
//printf("pub_topic %s\n", pub_topic);
slog(MISC_PRINT, SLOG_DEBUG, "pub_topic %s\n", pub_topic);
ret = MQTTPublish(&dmp_MqttClient, pub_topic, &pubmsg);
if (ret != 0)
{
//printf("MQTT_Publish failed,ret %d\n", ret);
slog(MISC_PRINT, SLOG_DEBUG, "MQTT_Publish failed,ret %d\n", ret);
}
else
{
//printf("MQTT_Publish success\n");
slog(MISC_PRINT, SLOG_DEBUG, "MQTT_Publish success\n");
}
}
usleep(1000*1000);
//imsi
char key_imsi[] = {"InIMSI"};
char imsi[32] = {0};
get_cfg_item("sim_imsi",imsi);
mbtk_pub_sim_payload(key_imsi, imsi);
//imei
char key_IMEI[] = {"DeviceIMEI"};
mbtk_pub_sim_payload(key_IMEI, deviceKey);
if (strlen(dmp_repo_config.HardVersion) > 0)
{
char key_HardVersion[] = {"HardVersion"};
char hard_version[10] = {0};
get_cfg_item("hw_version",hard_version);
if(hard_version[0] == '\0')
{
mbtk_pub_sim_payload(key_HardVersion, dmp_repo_config.HardVersion);
}
else
{
mbtk_pub_sim_payload(key_HardVersion, hard_version);
}
}
//connectionMode
char key_conn[] = {"connectionMode"};
char value_conn[] = {"4G"};
mbtk_pub_sim_payload(key_conn, value_conn);
//SIMType
char key_sim_type[] = {"SIMType"};
char sim_type[] = {"0"};
//int type,set sim_type_flag = 1
sim_type_flag = 1;
mbtk_pub_sim_payload(key_sim_type,sim_type);
char key_iccid[] = {"InICCID"};
char iccid[32] = {0};
memset(iccid, 0x0, sizeof(iccid));
get_cfg_item("ziccid",iccid);
mbtk_pub_sim_payload(key_iccid, iccid);
//software version
char module_ver_key[] = {"moduleSoftwareVersion"};
char module_ver[32] = {0};
memset(module_ver, 0x0, sizeof(module_ver));
get_cfg_item("cr_version",module_ver);
if(module_ver[0] == '\0')
{
mbtk_pub_sim_payload(module_ver_key,"LYNQ_CGMR_SW_V1.0");
}
else
{
mbtk_pub_sim_payload(module_ver_key,module_ver);
}
//hardware version
char module_hver_key[] = {"moduleHardwareVersion"};
char module_hver[10] = {0};
memset(module_hver, 0x0, sizeof(module_hver));
get_cfg_item("hw_version",module_hver);
mbtk_pub_sim_payload(module_hver_key,module_hver);
//apn
char key_apn[] = {"APN"};
char apn[100];
memset(apn,0x0,sizeof(apn));
get_cfg_item("wan_apn",apn);
//printf("ret %d,apn %s\n",ret,apn);
slog(MISC_PRINT, SLOG_DEBUG, "ret %d,apn %s\n",ret,apn);
mbtk_pub_sim_payload(key_apn,apn);
//printf("repo done\n");
slog(MISC_PRINT, SLOG_DEBUG, "repo done\n");
//time
char time_current[128] = {0};
char sign = '+';
time_t time_stamp;
time(&time_stamp);
struct tm *time_info = localtime(&time_stamp);
sprintf(time_current,"%d-%02d-%02d, %02d:%02d:%02d",
time_info->tm_year + 1900, time_info->tm_mon + 1, time_info->tm_mday,\
time_info->tm_hour, time_info->tm_min, time_info->tm_sec);
//printf("current time %s\n",time_current);
slog(MISC_PRINT, SLOG_DEBUG, "current time %s\n",time_current);
char key_time[] = {"moduleTime"};
mbtk_pub_sim_payload(key_time,time_current);
//netpayload
char net_payload[1024] = {0};
memset(net_payload, 0x0, sizeof(net_payload));
mbtk_get_net_payload(net_payload);
//printf("net_payload %s\n",net_payload);
slog(MISC_PRINT, SLOG_DEBUG, "net_payload %s\n",net_payload);
pubmsg2.payload = (void*)net_payload;
pubmsg2.payloadlen = strlen((char*)pubmsg2.payload);
pubmsg2.qos = QOS0;
pubmsg2.retained = 0;
pubmsg2.dup = 0;
ret = MQTTPublish(&dmp_MqttClient, pub_topic, &pubmsg2);
if(ret != 0)
{
//printf("mqtt publish err, %d\n", ret);
//dmp_MqttClient.ping_outstanding = 1;
slog(MISC_PRINT, SLOG_DEBUG, "mqtt publish err, %d\n", ret);
}
else
{
//printf("mqtt publish2 success\n");
slog(MISC_PRINT, SLOG_DEBUG, "mqtt publish2 success\n");
}
usleep(500*1000);
char ota_ver_topic[100] = {0};
char payload_Version[256] = {0};
char origin_version[48] = {0};
char inform_version[32] = {0};
get_cfg_item("cr_version", origin_version);
trim_version(origin_version,inform_version,sizeof(inform_version));
sprintf(ota_ver_topic,"$sys/%s/%s/ota/inform", productKey, deviceKey);
sprintf(payload_Version,"{\"messageId\":\"%d\",\"params\": {\"version\":\"%s\",\"otaType\": \"%s\"}}",message_id,inform_version,"default");
//printf("ota/inform topic %s\n", ota_ver_topic);
slog(MISC_PRINT, SLOG_DEBUG, "ota/inform topic %s\n", ota_ver_topic);
message_id ++;
//printf("payload_Version %s\n", payload_Version);
slog(MISC_PRINT, SLOG_DEBUG, "payload_Version %s\n", payload_Version);
pubmsg2.payload = (void*)payload_Version;
pubmsg2.payloadlen = strlen((char*)pubmsg2.payload);
ret = MQTTPublish(&dmp_MqttClient, ota_ver_topic, &pubmsg2);
//printf("ota/inform result %d\n",ret);
slog(MISC_PRINT, SLOG_DEBUG, "ota/inform result %d\n",ret);
sleep(1);
char wifi_payload[1024] = {0};
memset(wifi_payload, 0x0, sizeof(wifi_payload));
mbtk_get_wifi_payload(wifi_payload);
//printf("wifi_payload %s\n",wifi_payload);
slog(MISC_PRINT, SLOG_DEBUG, "wifi_payload %s\n",wifi_payload);
pubmsg3.payload = (void*)wifi_payload;
pubmsg3.payloadlen = strlen((char*)pubmsg3.payload);
pubmsg3.qos = QOS0;
pubmsg3.retained = 0;
pubmsg3.dup = 0;
ret = MQTTPublish(&dmp_MqttClient, pub_topic, &pubmsg3);
if(ret != 0)
{
//printf("mqtt publish err, %d\n", ret);
//dmp_MqttClient.ping_outstanding = 1;
slog(MISC_PRINT, SLOG_DEBUG, "mqtt publish err, %d\n", ret);
}
else
{
//printf("mqtt publish3 success\n");
slog(MISC_PRINT, SLOG_DEBUG, "mqtt publish3 success\n");
}
usleep(500*1000);
}
/**
* @brief Subscribe to topics
*
* Subscribe to two MQTT topics, one for OTA notification replies and the other for OTA upgrades.
*
* @return Subscription results, return 0 on success and non-zero on failure
*/
int mbtk_subscribe_topic()
{
char deviceKey[32] = {0};
int ret = 0;
get_cfg_item("imei", deviceKey);
char sub_ver_topic[100] = {0};
memset(sub_ver_topic, 0x0 ,sizeof(sub_ver_topic));
sprintf(sub_ver_topic,"$sys/%s/%s/ota/inform_reply", productKey, deviceKey);
ret = MQTTSubscribe(&dmp_MqttClient, sub_ver_topic, QOS0, dmp_sub_command_handle);
//printf("subscirbe %s,ret = %d\n",sub_ver_topic,ret);
slog(MISC_PRINT, SLOG_DEBUG, "subscirbe %s,ret = %d\n",sub_ver_topic,ret);
char ota_sub_topic[100] = {0};
memset(ota_sub_topic, 0x0 ,sizeof(ota_sub_topic));
sprintf(ota_sub_topic,"$sys/%s/%s/ota/upgrade", productKey, deviceKey);
ret = MQTTSubscribe(&dmp_MqttClient, ota_sub_topic, QOS0, dmp_upgrade_handle);
//printf("subscirbe %s,ret = %d\n",ota_sub_topic,ret);
slog(MISC_PRINT, SLOG_DEBUG, "subscirbe %s,ret = %d\n",ota_sub_topic,ret);
}
/**
* @brief Get file size
*
* Gets the size of the file (in bytes) by the given file pointer.
*
* @param fp File pointer
*
* @return File size (number of bytes), return 0 if the file failed to open
*/
int get_file_size(FILE* fp)
{
if (fp == NULL)
{
//printf("Failed to open file\n");
slog(MISC_PRINT, SLOG_DEBUG, "Failed to open file\n");
return 0;
}
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fclose(fp);
return size;
}
void dmp_demo(void)
{
char deviceKey[32] = {0};
char device_iccid[32] = {0};
char clientID[100] = {0};
char UserName[100] = {0};
char PassWord_temp[200] = {0};
char PassWord[200] = {0};
int operator = 1;
int mnc = 0;
char test_topic[200] = {0};
char test_pubtopic[200] = {0};
int ret = 0;
int retry_num = 0;
uint8_t passwd_hex[UNI_PASS_HEX_MAXLEN];
char new_clientID[100] = {0};
char new_UserName[100] = {0};
char token[100] = {0};
memset(new_clientID, 0x0, sizeof(new_clientID));
memset(new_UserName, 0x0, sizeof(new_UserName));
memset(token, 0x0, sizeof(token));
memset(deviceKey, 0x0, sizeof(deviceKey));
memset(clientID, 0x0, sizeof(clientID));
memset(device_iccid, 0x0, sizeof(device_iccid));
memset(UserName, 0x0, sizeof(UserName));
memset(PassWord, 0x0, sizeof(PassWord));
memset(PassWord_temp, 0x0, sizeof(PassWord));
memset(test_topic, 0x0, sizeof(test_topic));
get_cfg_item("imei", deviceKey);
signal(SIGINT, cfinish);
signal(SIGTERM, cfinish);
//get token config
FILE *fp = NULL;
int config_size = 0;
//config_fp = fopen(DONGLE_DMP_CONFIG, "rb");
//config_size = lynq_get_file_size(config_fp);
//RLOGD("config_size %d", config_size);
//if have a config file
if (config_size != 0)
{
lynq_dmp_cfg_t dmp_repo_config_temp;
//read config file
//****************
//
memset(&dmp_repo_config, 0x0, sizeof(dmp_repo_config));
memcpy(dmp_repo_config.productKey, dmp_repo_config_temp.productKey, strlen(dmp_repo_config_temp.productKey));
memcpy(dmp_repo_config.productSecret, dmp_repo_config_temp.productSecret, strlen(dmp_repo_config_temp.productSecret));
memcpy(dmp_repo_config.DeviceManu, dmp_repo_config_temp.DeviceManu, strlen(dmp_repo_config_temp.DeviceManu));
memcpy(dmp_repo_config.DeviceType, dmp_repo_config_temp.DeviceType, strlen(dmp_repo_config_temp.DeviceType));
memcpy(dmp_repo_config.HardVersion, dmp_repo_config_temp.HardVersion, strlen(dmp_repo_config_temp.HardVersion));
if (strlen(dmp_repo_config.productKey) > 0 && strlen(dmp_repo_config.productSecret) > 0)
{
memset(productKey, 0x0, sizeof(productKey));
memset(productSecret, 0x0, sizeof(productSecret));
memcpy(productKey, dmp_repo_config.productKey, strlen(dmp_repo_config.productKey));
memcpy(productSecret, dmp_repo_config.productSecret, strlen(dmp_repo_config.productSecret));
}
else
{
memset(productKey, 0x0, sizeof(productKey));
memset(productSecret, 0x0, sizeof(productSecret));
memcpy(productKey, MBTK_DMP_PRODUCT_KEY, strlen(MBTK_DMP_PRODUCT_KEY));
memcpy(productSecret, MBTK_DMP_PRODUCT_SECRET, strlen(MBTK_DMP_PRODUCT_SECRET));
}
}
else
{
memset(&dmp_repo_config, 0x0, sizeof(dmp_repo_config));
memset(productKey, 0x0, sizeof(productKey));
memset(productSecret, 0x0, sizeof(productSecret));
memcpy(productKey, MBTK_DMP_PRODUCT_KEY, strlen(MBTK_DMP_PRODUCT_KEY));
memcpy(productSecret, MBTK_DMP_PRODUCT_SECRET, strlen(MBTK_DMP_PRODUCT_SECRET));
memcpy(dmp_repo_config.DeviceManu, MBTK_DMP_DEVICE_MANU, strlen(MBTK_DMP_DEVICE_MANU));
memcpy(dmp_repo_config.DeviceType, MBTK_DMP_DEVICE_TYPE, strlen(MBTK_DMP_DEVICE_TYPE));
memcpy(dmp_repo_config.HardVersion, MBTK_DMP_HARD_VERSION, strlen(MBTK_DMP_HARD_VERSION));
}
//geticcid
get_cfg_item("ziccid", device_iccid);
sprintf(clientID,"%s|%s|0|2|%d", device_iccid, productKey, operator);
//printf("clientID %s\n", clientID);
slog(MISC_PRINT, SLOG_DEBUG, "clientID %s\n", clientID);
sprintf(UserName,"%s|%s", deviceKey, productKey);
//printf("UserName :%s \n",UserName);
slog(MISC_PRINT, SLOG_DEBUG, "UserName :%s \n",UserName);
sprintf(PassWord_temp,"%s%s%s", device_iccid,deviceKey, productKey);
//printf("PassWord_temp :%s \n",PassWord_temp);
slog(MISC_PRINT, SLOG_DEBUG, "PassWord_temp :%s \n",PassWord_temp);
utils_hmac_sha256((const uint8_t *)PassWord_temp, strlen(PassWord_temp), (const uint8_t *)productSecret, strlen(productSecret), passwd_hex);
util_hex2str(passwd_hex,UNI_PASS_HEX_MAXLEN,PassWord);
//printf("Password :%s \n",PassWord);
slog(MISC_PRINT, SLOG_DEBUG, "Password :%s \n",PassWord);
MQTTPacket_connectData connectData = MQTTPacket_connectData_initializer;
connectData.willFlag = 0;
connectData.MQTTVersion = 3;
connectData.clientID.cstring = clientID;
connectData.username.cstring = UserName;
connectData.password.cstring = PassWord;
connectData.keepAliveInterval = 295;
connectData.cleansession = 1;
FILE *token_fp = NULL;
token_fp = fopen(DMP_TOKEN_FILE, "ab+");
int token_filesize = 0;
token_filesize = get_file_size(token_fp);
//printf("token file size %d\n", token_filesize);
slog(MISC_PRINT, SLOG_DEBUG, "token file size %d\n", token_filesize);
//if don't have a token file, auto registration
if (0 == token_filesize)
{
NetworkInit(&dmp_MqttNetwork);
if(DMP_PORT == 8883)
{
//printf("networkConnectBySSL\n");
slog(MISC_PRINT, SLOG_DEBUG, "networkConnectBySSL\n");
NetworkConnectBySSL(&dmp_MqttNetwork, DMP_HOST, DMP_PORT, "");
}
else if(DMP_PORT == 1883)
{
//printf("networkConnect\n");
slog(MISC_PRINT, SLOG_DEBUG, "networkConnect\n");
NetworkConnect(&dmp_MqttNetwork, DMP_HOST, DMP_PORT);
}
MQTTClientInit(&dmp_MqttClient, &dmp_MqttNetwork, 1000, (unsigned char*)dmp_MqttSendbuf, sizeof(dmp_MqttSendbuf), (unsigned char*)dmp_MqttReadbuf, sizeof(dmp_MqttReadbuf));
if (MQTTConnect(&dmp_MqttClient, &connectData) != 0)
{
//printf("MQTT Connect fail\n");
slog(MISC_PRINT, SLOG_DEBUG, "MQTT Connect fail\n");
dmp_MqttClient.ping_outstanding = 1;
if(dmp_MqttSendbuf != NULL)
{
bzero(dmp_MqttSendbuf,strlen(dmp_MqttSendbuf));
}
if(dmp_MqttReadbuf != NULL)
{
bzero(dmp_MqttSendbuf,strlen(dmp_MqttSendbuf));
}
MQTTDisconnect(&dmp_MqttClient);
//printf("disconnect\n");
slog(MISC_PRINT, SLOG_DEBUG, "disconnect\n");
return;
}
else{
//printf("MQTT Connect success,topic\n");
slog(MISC_PRINT, SLOG_DEBUG, "MQTT Connect success,topic\n");
dmp_MqttClient.ping_outstanding = 0;
}
sprintf(test_topic,"$sys/%s/%s/ext/autoregist", productKey, deviceKey);
//printf("test_topic %s\n", test_topic);
slog(MISC_PRINT, SLOG_DEBUG, "test_topic %s\n", test_topic);
if(dmp_MqttClient.ping_outstanding == 0)
{
ret = MQTTSubscribe(&dmp_MqttClient, test_topic, QOS0, _mqtt_noreg_topic_handle);
if(ret != 0)
{
//printf("mqtt subscribe err\n, %d", ret);
slog(MISC_PRINT, SLOG_DEBUG, "mqtt subscribe err\n, %d", ret);
dmp_MqttClient.ping_outstanding = 1;
}
else
{
//printf("mqtt subscribe success,topic = %s\n", test_topic);
slog(MISC_PRINT, SLOG_DEBUG, "mqtt subscribe success,topic = %s\n", test_topic);
}
while (1)
{
//Yield
ret = MQTTYield(&dmp_MqttClient, 1000);
//printf("mqtt yield ret = %d\n",ret);
slog(MISC_PRINT, SLOG_DEBUG, "mqtt yield ret = %d\n",ret);
usleep(500*1000);
if(strlen(g_TokenStr) > 0)
{
break;
}
retry_num++;
if(retry_num > MQTT_DYNREG_SUBNUM)
{
//printf("mqtt dynreg sub retrynum done\n");
slog(MISC_PRINT, SLOG_DEBUG, "mqtt dynreg sub retrynum done\n");
break;
}
}
}
if(strlen(g_TokenStr) <= 0)
{
//printf("don't get token %s\n");
slog(MISC_PRINT, SLOG_DEBUG, "don't get token %s\n");
MQTTDisconnect(&dmp_MqttClient);
return;
}
else
{
FILE *token_write_fp = fopen(DMP_TOKEN_FILE, "wb");
if (token_write_fp == NULL) {
perror("Failed to create and open file for writing");
fclose(token_write_fp);
return;
}
fwrite(g_TokenStr, sizeof(char), strlen(g_TokenStr), token_write_fp);
fclose(token_write_fp);
//printf("File created and written with default token.\n");
slog(MISC_PRINT, SLOG_DEBUG, "File created and written with default token.\n");
MQTTDisconnect(&dmp_MqttClient);
NetworkDisconnect(&dmp_MqttNetwork);
}
}
else{
FILE *token_read_fp = fopen(DMP_TOKEN_FILE, "rb");
if(token_read_fp == NULL)
{
//printf("open token file fail\n");
slog(MISC_PRINT, SLOG_DEBUG, "open token file fail\n");
fclose(token_read_fp);
return;
}
size_t bytesRead = fread(g_TokenStr, sizeof(char), token_filesize, token_read_fp);
if (bytesRead > 0)
{
g_TokenStr[bytesRead] = '\0';
//printf("token %s\n",g_TokenStr);
slog(MISC_PRINT, SLOG_DEBUG, "token %s\n",g_TokenStr);
}
else
{
//printf("read token file fail\n");
slog(MISC_PRINT, SLOG_DEBUG, "read token file fail\n");
fclose(token_read_fp);
return;
}
fclose(token_read_fp);
}
//printf("autoregist success\n");
slog(MISC_PRINT, SLOG_DEBUG, "autoregist success\n");
sprintf(new_clientID,"%s|%s|0|-2|%d", device_iccid, productKey, operator);
sprintf(new_UserName,"%s|%s", deviceKey, productKey);
connectData2.willFlag = 0;
connectData2.MQTTVersion = 3;
connectData2.clientID.cstring = new_clientID;
connectData2.username.cstring = new_UserName;
connectData2.password.cstring = g_TokenStr;
connectData2.keepAliveInterval = 295;
connectData2.cleansession = 1;
//printf("new_clientID %s\n", new_clientID);
//printf("new_UserName %s\n", new_UserName);
slog(MISC_PRINT, SLOG_DEBUG, "new_clientID %s\n", new_clientID);
slog(MISC_PRINT, SLOG_DEBUG, "new_UserName %s\n", new_UserName);
//printf("networkInit\n");
slog(MISC_PRINT, SLOG_DEBUG, "networkInit\n");
NetworkInit(&dmp_MqttNetwork);
if(DMP_PORT == 8883)
{
//printf("networkConnectBySSL\n");
slog(MISC_PRINT, SLOG_DEBUG, "networkConnectBySSL\n");
NetworkConnectBySSL(&dmp_MqttNetwork, DMP_HOST, DMP_PORT, "");
}
else if(DMP_PORT == 1883)
{
//printf("networkConnect\n");
slog(MISC_PRINT, SLOG_DEBUG, "networkConnect\n");
NetworkConnect(&dmp_MqttNetwork, DMP_HOST, DMP_PORT);
}
//printf("MQTTClientInit\n");
slog(MISC_PRINT, SLOG_DEBUG, "MQTTClientInit\n");
MQTTClientInit(&dmp_MqttClient, &dmp_MqttNetwork, 1000, (unsigned char*)dmp_MqttSendbuf, sizeof(dmp_MqttSendbuf), (unsigned char*)dmp_MqttReadbuf, sizeof(dmp_MqttReadbuf));
//printf("MQTTConnect\n");
slog(MISC_PRINT, SLOG_DEBUG, "MQTTConnect\n");
ret = MQTTConnect(&dmp_MqttClient, &connectData2);
if (ret != 0)
{
//printf("mqtt connect fail,return %d\n",ret);
slog(MISC_PRINT, SLOG_DEBUG, "mqtt connect fail,return %d\n",ret);
dmp_MqttClient.ping_outstanding = 1;
MQTTDisconnect(&dmp_MqttClient);
if(dmp_MqttSendbuf != NULL)
{
bzero(dmp_MqttSendbuf,strlen(dmp_MqttSendbuf));
}
if(dmp_MqttReadbuf != NULL)
{
bzero(dmp_MqttSendbuf,strlen(dmp_MqttSendbuf));
}
//printf("disconnected\n");
slog(MISC_PRINT, SLOG_DEBUG, "disconnected\n");
return;
}
else
{
//printf("mqtt connect success\n");
slog(MISC_PRINT, SLOG_DEBUG, "mqtt connect success\n");
dmp_MqttClient.ping_outstanding = 0;
}
mbtk_dmp_repo_msg();
char sub_ver_topic[100] = {0};
memset(sub_ver_topic, 0x0 ,sizeof(sub_ver_topic));
sprintf(sub_ver_topic,"$sys/%s/%s/ota/inform_reply", productKey, deviceKey);
ret = MQTTSubscribe(&dmp_MqttClient, sub_ver_topic, QOS0, dmp_sub_command_handle);
//printf("subscirbe %s,ret = %d\n",sub_ver_topic,ret);
slog(MISC_PRINT, SLOG_DEBUG, "subscirbe %s,ret = %d\n",sub_ver_topic,ret);
char ota_sub_topic[100] = {0};
memset(ota_sub_topic, 0x0 ,sizeof(ota_sub_topic));
sprintf(ota_sub_topic,"$sys/%s/%s/ota/upgrade", productKey, deviceKey);
ret = MQTTSubscribe(&dmp_MqttClient, ota_sub_topic, QOS0, dmp_upgrade_handle);
//printf("subscirbe %s,ret = %d\n",ota_sub_topic,ret);
slog(MISC_PRINT, SLOG_DEBUG, "subscirbe %s,ret = %d\n",ota_sub_topic,ret);
//printf("dmp_repo_time %d\n", dmp_repo_time);
slog(MISC_PRINT, SLOG_DEBUG, "dmp_repo_time %d\n", dmp_repo_time);
if (dmp_repo_time > 0)
{
pthread_t yield_tid;
sleep(1);
pthread_create(&yield_tid, NULL, yield_thread, NULL);
pthread_join(yield_tid, NULL);
}
}
/**
* @brief Check network connection
*
* Run the ping command to check whether the specified IP address (110.242.68.66) can be connected.
* If the connection is successful, return 1; Otherwise, 0 is returned.
*
* @return If the connection is successful, return 1; Otherwise, 0 is returned.
*/
int check_network()
{
int i;
int count=0;
while(1)
{
i=system("ping -c 1 110.242.68.66");
//printf("ping -c 1 110.242.68.66 i=%d \n",i);
slog(MISC_PRINT, SLOG_DEBUG, "ping -c 1 110.242.68.66 i=%d \n",i);
count++;
if(i==0)
{
return 1;
}
if(count>3)
{
//printf("/n error cannot reach 110.242.68.66");
slog(MISC_PRINT, SLOG_DEBUG,"/n error cannot reach 110.242.68.66");
return 0;
}
}
}
void dmp_mqtt_task(void *arg)
{
int net_status = 1;
int fail_count = 0;
sleep(30);
while (1)
{
net_status = check_network();
if(fail_count > 5)
{
slog(MISC_PRINT, SLOG_DEBUG,"failed time > 5,exit");
break;
}
if (1 == net_status)
{
dmp_demo();
fail_count ++;
}
sleep(30);
}
//printf("dmp_mqtt_task start\n");
slog(MISC_PRINT, SLOG_DEBUG, "dmp_mqtt_task start\n");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t thread;
pthread_attr_t attr;
int ret = 0;
pthread_attr_init(&attr);
ret = pthread_create(&thread, &attr, dmp_mqtt_task, NULL);
//printf("ret = %d\n", ret);
slog(MISC_PRINT, SLOG_DEBUG, "ret = %d\n", ret);
if (ret != 0)
{
//printf("create dmp_mqtt_task failed\n");
slog(MISC_PRINT, SLOG_DEBUG, "create dmp_mqtt_task failed\n");
return -1;
}
pthread_join(thread, NULL);
}