#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#include "dy_utils/dy_common.h"
#include "common.h"
#include "dy_utils/cJSON.h"


static void external_subscribe_all(shanghai_S5_var_t *var)
{
    nodes_cfg_table_t *nodes = var->nodes_cfg_table; //节点信息
    node_cfg_t *node = NULL;
    mqtt_session_t *mqtt_session = var->session_ext;
    int i;

    dy_syslog(LOG_INFO, "subscribe all");
    if (nodes != NULL)
    {
        for (i = 0; i < nodes->node_cnt; i++)
        {
            node = &nodes->node[i];
            char topic[64] = {0};
            if (strcmp(node->app_key, APP_KEY) == 0)
            {
                // TCP的数据经由前置机到网关内部
                snprintf(topic, sizeof(topic), "F/%s/#", node->sn);
                mqtt_session_subscribe(mqtt_session, topic);
            }
        }
    }

    //前置机topic
    mqtt_session_subscribe(mqtt_session, "F/SearchSN");
}

// 建立与broker之间的MQTT连接
int external_client_init(shanghai_S5_var_t *var, char *filename)
{
    char clientId[MAX_CLIENT_ID_LEN] = {0};

    snprintf(clientId, MAX_CLIENT_ID_LEN, "SHS5_%s", var->sn_str);
    var->session_ext = mqtt_session_new(clientId, (void *)var);
    if (var->session_ext == NULL) return -1;

    load_server_config(var->session_ext, filename);
    mqtt_session_set_opts(var->session_ext, DEFAULT_QOS, KEEPALIVEINTERVAL);
    mqtt_session_set_callbacks(var->session_ext, external_mqtt_handle_recv_msg, NULL);

    mqtt_session_start(var->session_ext);
    external_subscribe_all(var);
}

