void MQTTConnector::createClient(const std::string &clientId) { if (mqttClient == NULL) { std::string address("tcp://"); address += brokerHost; address += ":"; address += brokerPort; // Pass Paho our allocation functions so we can track its memory usage within the rest // of the agents memory usage. Heap_set_allocator(&ibmras::common::memory::allocate, &ibmras::common::memory::deallocate); int rc = MQTTAsync_create(&mqttClient, address.c_str(), clientId.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL); if (rc != MQTTASYNC_SUCCESS) { IBMRAS_DEBUG_1(fine, "MQTTConnector: client create failed: %d", rc); } else { rc = MQTTAsync_setCallbacks(mqttClient, this, connectionLost, messageReceived, NULL); if (rc != MQTTASYNC_SUCCESS) { IBMRAS_DEBUG_1(fine, "MQTTConnector: setCallbacks failed: %d", rc); } } } }
void MQTT_init(void) { int rc=0;; MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(client, NULL, connlost, NULL, NULL); conn_opts.keepAliveInterval = 700; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); exit(-1); } printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", PAYLOAD, TOPIC, CLIENTID); /*while (!finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif */ sleep(3); }
/** * @name Create the MQTT client * @brief Create and initialize the mqtt plugin. * @param[in] servQuery is the service query being queried for * @return boolean, which specifies whether the connection is successfully established or not * * Establishes the connection with an MQTT broker. */ int init(void *servQuery) { ServiceQuery *serviceQuery = (ServiceQuery *) servQuery; MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer; int rc = 0; char uri[256]; if (serviceQuery->address != NULL) { sprintf(uri, "tcp://%s:%d", serviceQuery->address, serviceQuery->port); } else { sprintf(uri, "tcp://localhost:%d", serviceQuery->port); } // Default settings: int i = 0; MQTTAsync_token token; quietMode = 0; char clientID[256]; sprintf(clientID, "%s%d", CLIENTID, clientInstanceNumber++); MQTTAsync_create(&client, uri, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL); #if DEBUG MQTTAsync_setTraceCallback(handleTrace); MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR); #endif MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, deliveryComplete); conn_opts.cleansession = 0; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; conn_opts.keepAliveInterval = 0; conn_opts.retryInterval = 0; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); exit(1); } #if DEBUG printf("Waiting for connect\n"); #endif while (connected == 0 && finished == 0 && toStop == 0) { #if DEBUG printf("Waiting for connect: %d %d %d\n", connected, finished, toStop); #endif sleep(1); } return rc; }
int main(int argc, char* argv[]) { MQTTAsync client; MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; MQTTAsync_token token; int rc; int ch; MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); exit(EXIT_FAILURE); } while (!subscribed) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif if (finished) goto exit; do { ch = getchar(); } while (ch!='Q' && ch != 'q'); disc_opts.onSuccess = onDisconnect; if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start disconnect, return code %d\n", rc); exit(EXIT_FAILURE); } while (!disc_finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif exit: MQTTAsync_destroy(&client); return rc; }
int publish_main(void) { MQTTAsync client; MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; MQTTAsync_token token; int rc; MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer; MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(client, NULL, connlost, NULL, NULL); conn_opts.keepAliveInterval = 700; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); exit(-1); } printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", PAYLOAD, TOPIC, CLIENTID); /*while (!finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif */ sleep(3); int i=0; while(i<5){ i++; pubmsg.payload = msg;//PAYLOAD; pubmsg.payloadlen = strlen(msg);//PAYLOAD); msg[0]=msg[0]+1; if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start sendMessage, return code %d\n", rc); exit(-1); } } sleep(3600); MQTTAsync_destroy(&client); return rc; }
/******************************************************************** Test5: Connack return codes *********************************************************************/ int test5(struct Options options) { int subsqos = 2; MQTTAsync c; MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer; MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer; int rc = 0; char* test_topic = "C client test1"; test_finished = failures = 0; MyLog(LOGA_INFO, "Starting test 5 - connack return codes"); fprintf(xml, "<testcase classname=\"test4\" name=\"connack return codes\""); global_start_time = start_clock(); rc = MQTTAsync_create(&c, options.connection, "a clientid that is too long to be accepted", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL); assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc); if (rc != MQTTASYNC_SUCCESS) { MQTTAsync_destroy(&c); goto exit; } rc = MQTTAsync_setCallbacks(c, c, NULL, test1_messageArrived, NULL); assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); opts.onSuccess = test5_onConnect; opts.onFailure = test5_onConnectFailure; opts.context = c; MyLog(LOGA_DEBUG, "Connecting"); rc = MQTTAsync_connect(c, &opts); rc = 0; assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); if (rc != MQTTASYNC_SUCCESS) goto exit; while (!test_finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif MQTTAsync_destroy(&c); exit: MyLog(LOGA_INFO, "TEST5: test %s. %d tests run, %d failures.", (failures == 0) ? "passed" : "failed", tests, failures); write_test_result(); return failures; }
AWSIoTClient::AWSIoTClient(QString address, QString id, QObject *parent) : QObject(parent) { int rc = MQTTAsync_create(&client, address.toUtf8(), id.toUtf8(), MQTTCLIENT_PERSISTENCE_NONE, NULL); if (rc != MQTTASYNC_SUCCESS) { qFatal("Failed to create client %d\n", rc); } rc = MQTTAsync_setCallbacks(client, this, connectionLost, messageArrived, NULL); if (rc != MQTTASYNC_SUCCESS) { qFatal("Failed to set callbacks %d\n", rc); } }
bool mqtt_async::MqttClient::Connect(int interval, const ActDoneCB& cb) { int rc; if (!monitor_init) { MQTTAsync_connectionLost* cl = monitor.conn_lost_cb? &Monitor::ConnectionLost : nullptr; MQTTAsync_messageArrived* ma = monitor.msg_recv_cb? &Monitor::MsgRecv : nullptr; MQTTAsync_deliveryComplete* dc = monitor.delivery_done_cb ? &Monitor::Delivered : nullptr; rc = MQTTAsync_setCallbacks(client, &monitor, cl, ma, dc); if (rc != MQTTASYNC_SUCCESS) throw rc; monitor_init = true; } MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer; opts.keepAliveInterval = interval; opts.cleansession = 1; Token* tok = nullptr; std::shared_ptr<Token> stok; if (cb) { tok = new Token(this); stok = std::shared_ptr<Token>(tok); stok->act_done_cb = cb; SaveToken(stok); } opts.onSuccess = cb?&Token::OnSuccess : nullptr ; opts.onFailure = cb?&Token::OnFailed : nullptr ; opts.context = tok; if ((rc = MQTTAsync_connect(client, &opts)) != MQTTASYNC_SUCCESS) { if (tok) RemoveToken(tok); throw rc; } return true; }
/* * Function is used to initialize the MQTT connection handle "client" */ int init_mqtt_connection(MQTTAsync* client, char *address, int isRegistered, char* client_id, char* username, char* passwd) { MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer; int rc = MQTTASYNC_SUCCESS; MQTTAsync_create(client, address, client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(*client, NULL, NULL, subscribeMessage, NULL); #ifdef INFO syslog(LOG_INFO, "Connecting to %s with client Id: %s \n", address, client_id); #endif conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnectSuccess; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; //only when in registered mode, set the username/passwd and enable TLS if (isRegistered) { //currently only supported mech is token based. Need to change this in future. conn_opts.username = username; conn_opts.password = passwd; sslopts.trustStore = TRUSTSTORE; sslopts.enableServerCertAuth = 1; conn_opts.ssl = &sslopts; } if ((rc = MQTTAsync_connect(*client, &conn_opts)) != MQTTASYNC_SUCCESS) { #ifdef ERROR syslog(LOG_ERR, "Failed to start connect, return code %d\n", rc); #endif } return rc; }
int main(int argc, char* argv[]) { MQTTAsync client; MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; MQTTAsync_token token; int rc; MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(client, NULL, connlost, NULL, NULL); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); exit(-1); } printf("Waiting for publication of %s\n" "on topic %s for client with ClientID: %s\n", PAYLOAD, TOPIC, CLIENTID); while (!finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif MQTTAsync_destroy(&client); return rc; }
/* * Function is used to initialize the MQTT connection handle "client" */ int init_mqtt_connection(MQTTAsync* client, char *address, char* client_id) { MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; int rc = MQTTASYNC_SUCCESS; MQTTAsync_create(client, address, client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(*client, NULL, connlostqwe, NULL, NULL); #ifdef INFO syslog(LOG_INFO,"Connecting to %s with client Id: %s \n", address, client_id); #endif conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnectSuccess; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(*client, &conn_opts)) != MQTTASYNC_SUCCESS) { #ifdef ERROR syslog(LOG_ERR,"Failed to start connect, return code %d\n", rc); #endif } return rc; }
/********************************************************************* Test4: Send and receive big messages *********************************************************************/ int test4(struct Options options) { int subsqos = 2; MQTTAsync c; MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer; MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer; int rc = 0; char* test_topic = "C client test4"; test_finished = failures = 0; MyLog(LOGA_INFO, "Starting test 4 - big messages"); fprintf(xml, "<testcase classname=\"test4\" name=\"big messages\""); global_start_time = start_clock(); rc = MQTTAsync_create(&c, options.connection, "async_test_4", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL); assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc); if (rc != MQTTASYNC_SUCCESS) { MQTTAsync_destroy(&c); goto exit; } rc = MQTTAsync_setCallbacks(c, c, NULL, test4_messageArrived, NULL); assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); opts.keepAliveInterval = 20; opts.cleansession = 1; opts.username = "******"; opts.password = "******"; opts.MQTTVersion = options.MQTTVersion; opts.will = &wopts; opts.will->message = "will message"; opts.will->qos = 1; opts.will->retained = 0; opts.will->topicName = "will topic"; opts.will = NULL; opts.onSuccess = test4_onConnect; opts.onFailure = NULL; opts.context = c; MyLog(LOGA_DEBUG, "Connecting"); rc = MQTTAsync_connect(c, &opts); rc = 0; assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); if (rc != MQTTASYNC_SUCCESS) goto exit; while (!test_finished) #if defined(WIN32) Sleep(100); #else usleep(1000L); #endif MQTTAsync_destroy(&c); exit: MyLog(LOGA_INFO, "TEST4: test %s. %d tests run, %d failures.", (failures == 0) ? "passed" : "failed", tests, failures); write_test_result(); return failures; }
int main( int argc, const char* argv[] ){ MQTTAsync client; MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; int rc = ICP_SUCCESS; char str[128]; char topic[128]; char ch = 'a'; char cmd[128] = ""; char sub_cmd[8][8]; char *pch; int i; mac_addr_t receiver; printf("\n\n\n\n\n"); // MQTT setup, connection and subscribe's MQTTAsync_create(&client, ADDRESS, mac_addrs[local_mac_addr], MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(client, NULL, connlost, msgarrvd, NULL); p_client = &client; CHECK_MEM(p_client); mqtt_enable_debug_output(TRUE); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS){ MQTT_DEBUG("Failed to start connect, return code %d\n", rc); exit(-1); } while (!connected); // CHECK_ERR(print_packet(NULL) == -1, "failed with p_packet=NULL"); // CHECK_ERR(print_packet(&packet) == 0, "failed with valid args"); // CHECK_ERR(icp_bytes_out_cb( (const uint8_t *)NULL, 10, NULL) == 0, "failed with output_byte_array=NULL"); // CHECK_ERR(icp_bytes_out_cb( (const uint8_t *)str, 0, NULL) == 0, "failed with array_len=0"); // strcpy(str, "Hello"); // CHECK_ERR(icp_bytes_out_cb( (const uint8_t *)str, 10, NULL) == 0, "failed with array_len:10!=strlen(output_byte_array):%s", str); // strcpy(str, "Hello"); // CHECK_ERR(icp_bytes_out_cb( (const uint8_t *)str, strlen(str), NULL) == strlen(str), "failed with valid args"); // CHECK_ERR(icp_packet_received_cb(NULL, NULL) == -1, "failed with p_packet=NULL"); // CHECK_ERR(icp_packet_received_cb(&packet, NULL) == 0, "failed with valid args"); // CHECK_ERR(icp_error_cb(ICP_SUCCESS, packet.data, packet.data_length, NULL) == -1, "failed with invalid packet"); // packet.data = (uint8_t *)&str; // CHECK_ERR(icp_error_cb(ICP_SUCCESS, packet.data, packet.data_length, NULL) == 0, "failed with valid args"); // while(TRUE); if (finished) goto exit; if (FALSE) { LOG_INFO("Sending clean..."); sent = FALSE; strcpy(str, "clean"); strcpy(topic, topic_names[TOPIC_SIMULATOR_BASE]); pubmsg.payload = (char*)str; pubmsg.payloadlen = strlen(str); pubmsg.qos = QOS; pubmsg.retained = 0; sendmsg(client, topic, &pubmsg); while (!sent) ; LOG_INFO("Sending 'eps' to pc..."); sent = FALSE; strcpy(str, "eps"); strcpy(topic, topic_names[TOPIC_SIMULATOR_BASE]); strcat(topic, mac_addrs[NODE_PC]); pubmsg.payload = (char*)str; pubmsg.payloadlen = strlen(str); pubmsg.qos = QOS; pubmsg.retained = 0; sendmsg(client, topic, &pubmsg); while (!sent) ; LOG_INFO("Sending 'cdhs' to cam..."); sent = FALSE; strcpy(str, "cdhs"); strcpy(topic, topic_names[TOPIC_SIMULATOR_BASE]); strcat(topic, mac_addrs[NODE_CAM]); pubmsg.payload = (char*)str; pubmsg.payloadlen = strlen(str); pubmsg.qos = QOS; pubmsg.retained = 0; sendmsg(client, topic, &pubmsg); while (!sent) ; LOG_INFO("Sending 'pc' to cdhs..."); sent = FALSE; strcpy(str, "pc"); strcpy(topic, topic_names[TOPIC_SIMULATOR_BASE]); strcat(topic, mac_addrs[NODE_CDHS]); pubmsg.payload = (char*)str; pubmsg.payloadlen = strlen(str); pubmsg.qos = QOS; pubmsg.retained = 0; sendmsg(client, topic, &pubmsg); while (!sent) ; LOG_INFO("Sending 'cdhs' to eps..."); sent = FALSE; strcpy(str, "cdhs"); strcpy(topic, topic_names[TOPIC_SIMULATOR_BASE]); strcat(topic, mac_addrs[NODE_EPS]); pubmsg.payload = (char*)str; pubmsg.payloadlen = strlen(str); pubmsg.qos = QOS; pubmsg.retained = 0; sendmsg(client, topic, &pubmsg); while (!sent) ; LOG_INFO("Sending update..."); sent = FALSE; strcpy(str, "update"); strcpy(topic, topic_names[TOPIC_SIMULATOR_BASE]); pubmsg.payload = (char*)str; pubmsg.payloadlen = strlen(str); pubmsg.qos = QOS; pubmsg.retained = 0; sendmsg(client, topic, &pubmsg); while (!sent) ; } LOG_INFO("Running..."); while (TRUE) { ch = getchar(); if (strncmp(&ch, "\n", 1) != 0) { strcat(cmd, &ch); } else { LOG_INFO("Got cmd: %s", cmd); pch = strtok (cmd," "); i = 0; while (pch != NULL) { strcpy(sub_cmd[i++], pch); DEBUG("sub_cmd[%d] = %s - %s", i-1, sub_cmd[i-1], (strncmp(sub_cmd[i-1], "set", 3) == 0 ? "TRUE" : "FALSE")); pch = strtok (NULL, " "); } receiver = INVALID_MAC_ADDR; if ( strncmp(sub_cmd[0], "cam", 3) == 0 ) { receiver = NODE_CAM; } else if ( strncmp(sub_cmd[0], "cdhs", 4) == 0 ) { receiver = NODE_CDHS; } else if ( strncmp(sub_cmd[0], "pc", 2) == 0 ) { receiver = NODE_PC; } else if ( strncmp(sub_cmd[0], "eps", 3) == 0 ) { receiver = NODE_EPS; } else if ( strncmp(sub_cmd[0], "test", 4) == 0 ) { receiver = NODE_TEST; } else if ( strncmp(sub_cmd[0], "bus", 3) == 0 ) { receiver = NODE_BUS; } else if ( strncmp(sub_cmd[0], "all", 4) == 0 ) { receiver = BROADCAST; } strcpy(topic, topic_names[TOPIC_SIMULATOR_BASE]); if (receiver != INVALID_MAC_ADDR && receiver != BROADCAST) { strcat(topic, mac_addrs[receiver]); } if (strncmp(sub_cmd[0], "q", 1) == 0) { LOG_INFO("Quiting..."); break; } else if (strlen(cmd) == 0) { LOG_INFO("Empty cmd..."); goto end; }else if (strncmp(sub_cmd[0], "clean", 5) == 0 || strncmp(sub_cmd[0], "update", 6) == 0 || strncmp(sub_cmd[0], "reset", 5) == 0 || strncmp(sub_cmd[0], "stopupdate", 10) == 0 || strncmp(sub_cmd[0], "sync", 4) == 0 || strncmp(sub_cmd[0], "time", 4) == 0) { LOG_INFO("Sending '%s' to all.", sub_cmd[0]); sent = FALSE; strcpy(str, sub_cmd[0]); if (strncmp(sub_cmd[0], "sync", 4) == 0) { synctime(); } } else if (strncmp(sub_cmd[1], "clean", 5) == 0 || strncmp(sub_cmd[1], "update", 6) == 0|| strncmp(sub_cmd[1], "stopupdate", 10) == 0 || strncmp(sub_cmd[1], "reset", 5) == 0 || strncmp(sub_cmd[1], "time", 4) == 0) { CHECK_EXIT(receiver != NUM_OF_NODES, "Invalid receiver."); LOG_INFO("Sending '%s' to %s.", sub_cmd[1], mac_addrs[receiver]); strcpy(str, sub_cmd[1]); }else if (strncmp(sub_cmd[1], "ping", 4) == 0 ) { CHECK_EXIT(receiver != NUM_OF_NODES, "Invalid receiver."); if ( strncmp(sub_cmd[2], "cdhs", 4) == 0 || strncmp(sub_cmd[2], "cam", 3) == 0 || strncmp(sub_cmd[2], "pc", 2) == 0 || strncmp(sub_cmd[2], "eps", 3) == 0 || strncmp(sub_cmd[2], "bus", 3) == 0 ) { LOG_INFO("Sending '%s' to %s...", sub_cmd[2], mac_addrs[receiver]); } else { LOG_INFO("Failed to cmd to send.") goto fail; } strcpy(str, sub_cmd[2]); }else if (strncmp(sub_cmd[1], "set", 3) == 0 ) { CHECK_EXIT(receiver != INVALID_MAC_ADDR, "Invalid receiver."); if ( (strncmp(sub_cmd[2], "icp", 3) == 0 || strncmp(sub_cmd[2], "mqtt", 4) == 0 || strncmp(sub_cmd[2], "sys", 3) == 0 || strncmp(sub_cmd[2], "all", 3) == 0) && (strncmp(sub_cmd[3], "debug", 5) == 0 || strncmp(sub_cmd[3], "err", 3) == 0 || strncmp(sub_cmd[3], "warn", 4) == 0 || strncmp(sub_cmd[3], "info", 4) == 0 || strncmp(sub_cmd[3], "all", 3) == 0) && (strncmp(sub_cmd[4], "true", 4) == 0 || strncmp(sub_cmd[4], "false", 5) == 0)) { LOG_INFO("Sending '%s %s %s %s' to %s...", sub_cmd[1], sub_cmd[2], sub_cmd[3], sub_cmd[4], mac_addrs[receiver]); strcpy(str, sub_cmd[1]); strcat(str, " "); strcat(str, sub_cmd[2]); strcat(str, " "); strcat(str, sub_cmd[3]); strcat(str, " "); strcat(str, sub_cmd[4]); } else /*if ( (strncmp(sub_cmd[2], "icp", 3) == 0 || strncmp(sub_cmd[2], "mqtt", 4) == 0 || strncmp(sub_cmd[2], "sys", 3) == 0) && (strncmp(sub_cmd[3], "debug", 5) == 0 || strncmp(sub_cmd[3], "err", 3) == 0 || strncmp(sub_cmd[3], "warn", 4) == 0 || strncmp(sub_cmd[3], "info", 4) == 0) && (strncmp(sub_cmd[4], "true", 4) == 0 || strncmp(sub_cmd[4], "false", 5) == 0)) { LOG_INFO("Sending '%s %s %s %s' to %s...", sub_cmd[1], sub_cmd[2], sub_cmd[3], sub_cmd[4], mac_addrs[receiver]); */{ LOG_WARN("Failed to send cmd.") LOG_INFO("command example: [eps|pc|...|all] set [icp|sys|mqtt|all] [debug|err|warn|info|all] [true|false]"); goto fail; } } else { goto fail; } sent = FALSE; pubmsg.payload = (char*)str; pubmsg.payloadlen = strlen(str); pubmsg.qos = QOS; pubmsg.retained = 0; LOG_INFO("Sending '%s' to '%s'", str, topic); sendmsg(client, topic, &pubmsg); while (!sent) ; fail: end: LOG_INFO("Clearing cmd buffer."); strcpy(cmd, ""); for(i=0;i<8;i++) { strcpy(sub_cmd[i], ""); } }
int main(int argc, char** argv) { MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer; MQTTAsync_responseOptions pub_opts = MQTTAsync_responseOptions_initializer; MQTTAsync_createOptions create_opts = MQTTAsync_createOptions_initializer; MQTTAsync client; char* topic = NULL; char* buffer = NULL; int rc = 0; char url[100]; if (argc < 2) usage(); getopts(argc, argv); sprintf(url, "%s:%s", opts.host, opts.port); if (opts.verbose) printf("URL is %s\n", url); topic = argv[1]; printf("Using topic %s\n", topic); create_opts.sendWhileDisconnected = 1; rc = MQTTAsync_createWithOptions(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL, &create_opts); signal(SIGINT, cfinish); signal(SIGTERM, cfinish); rc = MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, NULL); myconnect(&client); buffer = malloc(opts.maxdatalen); while (!toStop) { int data_len = 0; int delim_len = 0; delim_len = (int)strlen(opts.delimiter); do { buffer[data_len++] = getchar(); if (data_len > delim_len) { /* printf("comparing %s %s\n", opts.delimiter, &buffer[data_len - delim_len]); */ if (strncmp(opts.delimiter, &buffer[data_len - delim_len], delim_len) == 0) break; } } while (data_len < opts.maxdatalen); if (opts.verbose) printf("Publishing data of length %d\n", data_len); pub_opts.onSuccess = onPublish; pub_opts.onFailure = onPublishFailure; do { rc = MQTTAsync_send(client, topic, data_len, buffer, opts.qos, opts.retained, &pub_opts); } while (rc != MQTTASYNC_SUCCESS); } printf("Stopping\n"); free(buffer); disc_opts.onSuccess = onDisconnect; if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start disconnect, return code %d\n", rc); exit(EXIT_FAILURE); } while (!disconnected) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif MQTTAsync_destroy(&client); return EXIT_SUCCESS; }
/** * The main entry point of the sample. * * This method handles parsing the arguments specified on the * command-line before performing the specified action. */ int main(int argc, char** argv) { int rc = 0; int ch; char url[256]; // Default settings: int i=0; MQTTAsync client; MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; MQTTAsync_token token; signal(SIGINT, handleSignal); signal(SIGTERM, handleSignal); quietMode = 0; // Parse the arguments - for (i=1; i<argc; i++) { // Check this is a valid argument if (strlen(argv[i]) == 2 && argv[i][0] == '-') { char arg = argv[i][1]; // Handle the no-value arguments if (arg == 'h' || arg == '?') { printHelp(); return 255; } else if (arg == 'q') { quietMode = 1; continue; } // Validate there is a value associated with the argument if (i == argc - 1 || argv[i+1][0] == '-') { printf("Missing value for argument: %s\n", argv[i]); printHelp(); return 255; } switch(arg) { case 'a': options.action = argv[++i]; break; case 't': options.topic = argv[++i]; break; case 'm': options.message = argv[++i]; break; case 's': options.qos = atoi(argv[++i]); break; case 'c': options.message_count = atoi(argv[++i]); break; case 'b': options.broker = argv[++i]; break; case 'p': options.port = argv[++i]; break; default: printf("Unrecognised argument: %s\n", argv[i]); printHelp(); return 255; } } else { printf("Unrecognised argument: %s\n", argv[i]); printHelp(); return 255; } } // Validate the provided arguments if (strcmp(options.action, "publish") != 0 && strcmp(options.action, "subscribe") != 0) { printf("Invalid action: %s\n", options.action); printHelp(); return 255; } if (options.qos < 0 || options.qos > 2) { printf("Invalid QoS: %d\n", options.qos); printHelp(); return 255; } if (options.topic == NULL || ( options.topic != NULL && strlen(options.topic) == 0) ) { // Set the default topic according to the specified action if (strcmp(options.action, "publish") == 0) options.topic = "MQTTV3ASample/C/v3"; else options.topic = "MQTTV3ASample/#"; } // Construct the full broker URL and clientId sprintf(url, "tcp://%s:%s", options.broker, options.port); sprintf(clientId, "SampleCV3A_%s", options.action); MQTTAsync_create(&client, url, clientId, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setTraceCallback(handleTrace); MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR); MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, deliveryComplete); conn_opts.cleansession = 0; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; conn_opts.keepAliveInterval = 0; conn_opts.retryInterval = 0; //conn_opts.maxInflight= 30; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); goto exit; } printf("Waiting for connect\n"); while (connected == 0 && finished == 0 && toStop == 0) { printf("Waiting for connect: %d %d %d\n", connected, finished, toStop); usleep(10000L); } MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer; printf("Waiting for connect: %d %d %d\n", connected, finished, toStop); printf("Successful connection\n"); if (connected == 1 && strcmp(options.action, "publish") == 0) { unsigned long i; struct timeval tv; gettimeofday(&tv,NULL); printf("start seconds : %ld\n",tv.tv_sec); for (i = 0; i < options.message_count; i++) { opts.onSuccess = onSend; opts.onFailure = onSendFailure; opts.context = client; pubmsg.payload = options.message; pubmsg.payloadlen = strlen(options.message); pubmsg.qos = options.qos; pubmsg.retained = 0; deliveredtoken = 0; usleep(100); if ((rc = MQTTAsync_sendMessage(client, options.topic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start sendMessage, return code %d\n", rc); exit(-1); } } gettimeofday(&tv,NULL); printf("end seconds : %ld\n",tv.tv_sec); } else if (strcmp(options.action, "subscribe") == 0) { opts.onSuccess = onSubscribe; opts.onFailure = onSubscribeFailure; opts.context = client; if ((rc = MQTTAsync_subscribe(client, options.topic, options.qos, &opts)) != MQTTASYNC_SUCCESS) { printf("Failed to subscribe, return code %d\n", rc); exit(-1); } } while (!finished) { #if defined(WIN32) Sleep(100); #else usleep(1000L); #endif if (toStop == 1) { MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer; opts.onSuccess = onDisconnect; opts.context = client; printf("Entering disconnection phase\n"); if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start disconnect, return code %d\n", rc); exit(-1); } toStop = 0; } } exit: printf("calling destroy\n"); MQTTAsync_destroy(&client); return rc; }
int test3(struct Options options) { char* testname = "test3"; int subsqos = 2; MQTTAsync c, d; MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer; MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer; MQTTAsync_createOptions createOptions = MQTTAsync_createOptions_initializer; int rc = 0; int count = 0; char clientidc[50]; char clientidd[50]; int i = 0; MQTTAsync_token *tokens; sprintf(willTopic, "paho-test9-3-%s", unique); sprintf(clientidc, "paho-test9-3-c-%s", unique); sprintf(clientidd, "paho-test9-3-d-%s", unique); sprintf(test_topic, "paho-test9-3-test topic %s", unique); test3Finished = 0; failures = 0; MyLog(LOGA_INFO, "Starting Offline buffering 3 - messages while disconnected"); fprintf(xml, "<testcase classname=\"test3\" name=\"%s\"", testname); global_start_time = start_clock(); createOptions.sendWhileDisconnected = 1; rc = MQTTAsync_createWithOptions(&c, options.proxy_connection, clientidc, MQTTCLIENT_PERSISTENCE_DEFAULT, NULL, &createOptions); assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d \n", rc); if (rc != MQTTASYNC_SUCCESS) { MQTTAsync_destroy(&c); goto exit; } rc = MQTTAsync_create(&d, options.connection, clientidd, MQTTCLIENT_PERSISTENCE_DEFAULT, NULL); assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d \n", rc); if (rc != MQTTASYNC_SUCCESS) { MQTTAsync_destroy(&c); goto exit; } opts.keepAliveInterval = 20; opts.cleansession = 1; //opts.username = "******"; //opts.password = "******"; rc = MQTTAsync_setCallbacks(d, d, NULL, test3_messageArrived, NULL); assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); opts.will = NULL; /* don't need will for this client, as it's going to be connected all the time */ opts.context = d; opts.onSuccess = test3dOnConnect; opts.onFailure = test3dOnFailure; MyLog(LOGA_DEBUG, "Connecting client d"); rc = MQTTAsync_connect(d, &opts); assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d ", rc); if (rc != MQTTASYNC_SUCCESS) { failures++; goto exit; } /* wait until d is ready: connected and subscribed */ count = 0; while (!test3dReady && ++count < 10000) MySleep(100); assert("Count should be less than 10000", count < 10000, "count was %d", count); /* wrong */ rc = MQTTAsync_setConnected(c, c, test3cConnected); assert("Good rc from setConnectedCallback", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); /* let client c go: connect, and send disconnect command to proxy */ opts.will = &wopts; opts.will->message = "will message"; opts.will->qos = 1; opts.will->retained = 0; opts.will->topicName = willTopic; opts.onSuccess = test3cOnConnect; opts.onFailure = test3cOnFailure; opts.context = c; opts.cleansession = 0; opts.automaticReconnect = 1; MyLog(LOGA_DEBUG, "Connecting client c"); rc = MQTTAsync_connect(c, &opts); assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d ", rc); if (rc != MQTTASYNC_SUCCESS) { failures++; goto exit; } /* wait for will message */ while (!test3_will_message_received && ++count < 10000) MySleep(100); MyLog(LOGA_DEBUG, "Now we can send some messages to be buffered"); test3c_connected = 0; /* send some messages. Then reconnect (check connected callback), and check that those messages are received */ for (i = 0; i < 3; ++i) { char buf[50]; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer; sprintf(buf, "QoS %d message", i); pubmsg.payload = buf; pubmsg.payloadlen = strlen(pubmsg.payload) + 1; pubmsg.qos = i; pubmsg.retained = 0; rc = MQTTAsync_sendMessage(c, test_topic, &pubmsg, &opts); assert("Good rc from sendMessage", rc == MQTTASYNC_SUCCESS, "rc was %d ", rc); } rc = MQTTAsync_getPendingTokens(c, &tokens); assert("Good rc from getPendingTokens", rc == MQTTASYNC_SUCCESS, "rc was %d ", rc); i = 0; if (tokens) { while (tokens[i] != -1) ++i; MQTTAsync_free(tokens); } assert("Number of getPendingTokens should be 3", i == 3, "i was %d ", i); /* wait for client to be reconnected */ while (!test3c_connected == 0 && ++count < 10000) MySleep(100); /* wait for success or failure callback */ while (test3_messages_received < 3 && ++count < 10000) MySleep(100); rc = MQTTAsync_getPendingTokens(c, &tokens); assert("Good rc from getPendingTokens", rc == MQTTASYNC_SUCCESS, "rc was %d ", rc); i = 0; if (tokens) { while (tokens[i] != -1) ++i; MQTTAsync_free(tokens); } assert("Number of getPendingTokens should be 0", i == 0, "i was %d ", i); rc = MQTTAsync_disconnect(c, NULL); assert("Good rc from disconnect", rc == MQTTASYNC_SUCCESS, "rc was %d ", rc); rc = MQTTAsync_disconnect(d, NULL); assert("Good rc from disconnect", rc == MQTTASYNC_SUCCESS, "rc was %d ", rc); exit: MQTTAsync_destroy(&c); MQTTAsync_destroy(&d); MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.", (failures == 0) ? "passed" : "failed", testname, tests, failures); write_test_result(); return failures; }
int main(int argc, char** argv) { MQTTAsync client; MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer; int rc = 0; char url[100]; if (argc < 2) usage(); topic = argv[1]; if (strchr(topic, '#') || strchr(topic, '+')) opts.showtopics = 1; if (opts.showtopics) printf("topic is %s\n", topic); getopts(argc, argv); sprintf(url, "%s:%s", opts.host, opts.port); rc = MQTTAsync_create(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, NULL); signal(SIGINT, cfinish); signal(SIGTERM, cfinish); conn_opts.keepAliveInterval = opts.keepalive; conn_opts.cleansession = 1; conn_opts.username = opts.username; conn_opts.password = opts.password; conn_opts.onSuccess = onConnect; conn_opts.onFailure = onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); exit(EXIT_FAILURE); } while (!subscribed) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif if (finished) goto exit; while (!finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif disc_opts.onSuccess = onDisconnect; if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start disconnect, return code %d\n", rc); exit(EXIT_FAILURE); } while (!disconnected) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif exit: MQTTAsync_destroy(&client); return EXIT_SUCCESS; }
int janus_mqtt_init(janus_transport_callbacks *callback, const char *config_path) { if(callback == NULL || config_path == NULL) { /* Invalid arguments */ return -1; } /* Initializing context */ janus_mqtt_context *ctx = g_malloc0(sizeof(struct janus_mqtt_context)); ctx->gateway = callback; context_ = ctx; /* Prepare the transport session (again, just one) */ mqtt_session = janus_transport_session_create(context_, NULL); /* Read configuration */ char filename[255]; g_snprintf(filename, 255, "%s/%s.cfg", config_path, JANUS_MQTT_PACKAGE); JANUS_LOG(LOG_VERB, "Configuration file: %s\n", filename); janus_config *config = janus_config_parse(filename); if(config != NULL) { janus_config_print(config); } /* Handle configuration */ janus_config_item *url_item = janus_config_get_item_drilldown(config, "general", "url"); const char *url = g_strdup((url_item && url_item->value) ? url_item->value : "tcp://localhost:1883"); janus_config_item *client_id_item = janus_config_get_item_drilldown(config, "general", "client_id"); const char *client_id = g_strdup((client_id_item && client_id_item->value) ? client_id_item->value : "guest"); janus_config_item *username_item = janus_config_get_item_drilldown(config, "general", "username"); ctx->connect.username = g_strdup((username_item && username_item->value) ? username_item->value : "guest"); janus_config_item *password_item = janus_config_get_item_drilldown(config, "general", "password"); ctx->connect.password = g_strdup((password_item && password_item->value) ? password_item->value : "guest"); janus_config_item *json_item = janus_config_get_item_drilldown(config, "general", "json"); if(json_item && json_item->value) { /* Check how we need to format/serialize the JSON output */ if(!strcasecmp(json_item->value, "indented")) { /* Default: indented, we use three spaces for that */ json_format_ = JSON_INDENT(3) | JSON_PRESERVE_ORDER; } else if(!strcasecmp(json_item->value, "plain")) { /* Not indented and no new lines, but still readable */ json_format_ = JSON_INDENT(0) | JSON_PRESERVE_ORDER; } else if(!strcasecmp(json_item->value, "compact")) { /* Compact, so no spaces between separators */ json_format_ = JSON_COMPACT | JSON_PRESERVE_ORDER; } else { JANUS_LOG(LOG_WARN, "Unsupported JSON format option '%s', using default (indented)\n", json_item->value); json_format_ = JSON_INDENT(3) | JSON_PRESERVE_ORDER; } } /* Check if we need to send events to handlers */ janus_config_item *events = janus_config_get_item_drilldown(config, "general", "events"); if(events != NULL && events->value != NULL) notify_events = janus_is_true(events->value); if(!notify_events && callback->events_is_enabled()) { JANUS_LOG(LOG_WARN, "Notification of events to handlers disabled for %s\n", JANUS_MQTT_NAME); } /* Check if we need to enable SSL support */ janus_config_item *ssl = janus_config_get_item_drilldown(config, "general", "ssl_enable"); if(ssl && ssl->value && janus_is_true(ssl->value)) { if(strstr(url, "ssl://") != url) JANUS_LOG(LOG_WARN, "SSL enabled, but MQTT url doesn't start with ssl://...\n"); ctx->ssl_enable = TRUE; janus_config_item *cacertfile = janus_config_get_item_drilldown(config, "general", "cacertfile"); if(!cacertfile || !cacertfile->value) { JANUS_LOG(LOG_FATAL, "Missing CA certificate for MQTT integration...\n"); goto error; } ctx->cacert_file = g_strdup(cacertfile->value); janus_config_item *certfile = janus_config_get_item_drilldown(config, "general", "certfile"); ctx->cert_file = (certfile && certfile->value) ? g_strdup(certfile->value) : NULL; janus_config_item *keyfile = janus_config_get_item_drilldown(config, "general", "keyfile"); ctx->key_file = (keyfile && keyfile->value) ? g_strdup(keyfile->value) : NULL; if(ctx->cert_file && !ctx->key_file) { JANUS_LOG(LOG_FATAL, "Certificate is set but key isn't for MQTT integration...\n"); goto error; } if(!ctx->cert_file && ctx->key_file) { JANUS_LOG(LOG_FATAL, "Key is set but certificate isn't for MQTT integration...\n"); goto error; } janus_config_item *verify = janus_config_get_item_drilldown(config, "general", "verify_peer"); ctx->verify_peer = (verify && verify->value && janus_is_true(verify->value)) ? TRUE : FALSE; } else { JANUS_LOG(LOG_INFO, "MQTT SSL support disabled\n"); if(strstr(url, "ssl://") == url) JANUS_LOG(LOG_WARN, "SSL disabled, but MQTT url starts with ssl:// instead of tcp://...\n"); } /* Connect configuration */ janus_config_item *keep_alive_interval_item = janus_config_get_item_drilldown(config, "general", "keep_alive_interval"); ctx->connect.keep_alive_interval = (keep_alive_interval_item && keep_alive_interval_item->value) ? atoi(keep_alive_interval_item->value) : 20; janus_config_item *cleansession_item = janus_config_get_item_drilldown(config, "general", "cleansession"); ctx->connect.cleansession = (cleansession_item && cleansession_item->value) ? atoi(cleansession_item->value) : 0; /* Disconnect configuration */ janus_config_item *disconnect_timeout_item = janus_config_get_item_drilldown(config, "general", "disconnect_timeout"); ctx->disconnect.timeout = (disconnect_timeout_item && disconnect_timeout_item->value) ? atoi(disconnect_timeout_item->value) : 100; janus_config_item *enable_item = janus_config_get_item_drilldown(config, "general", "enable"); if(enable_item && enable_item->value && janus_is_true(enable_item->value)) { janus_mqtt_api_enabled_ = TRUE; /* Subscribe configuration */ { janus_config_item *topic_item = janus_config_get_item_drilldown(config, "general", "subscribe_topic"); if(!topic_item || !topic_item->value) { JANUS_LOG(LOG_FATAL, "Missing topic for incoming messages for MQTT integration...\n"); goto error; } ctx->subscribe.topic = g_strdup(topic_item->value); janus_config_item *qos_item = janus_config_get_item_drilldown(config, "general", "subscribe_qos"); ctx->subscribe.qos = (qos_item && qos_item->value) ? atoi(qos_item->value) : 1; } /* Publish configuration */ { janus_config_item *topic_item = janus_config_get_item_drilldown(config, "general", "publish_topic"); if(!topic_item || !topic_item->value) { JANUS_LOG(LOG_FATAL, "Missing topic for outgoing messages for MQTT integration...\n"); goto error; } ctx->publish.topic = g_strdup(topic_item->value); janus_config_item *qos_item = janus_config_get_item_drilldown(config, "general", "publish_qos"); ctx->publish.qos = (qos_item && qos_item->value) ? atoi(qos_item->value) : 1; } } else { janus_mqtt_api_enabled_ = FALSE; ctx->subscribe.topic = NULL; ctx->publish.topic = NULL; } /* Admin configuration */ janus_config_item *admin_enable_item = janus_config_get_item_drilldown(config, "admin", "admin_enable"); if(admin_enable_item && admin_enable_item->value && janus_is_true(admin_enable_item->value)) { janus_mqtt_admin_api_enabled_ = TRUE; /* Admin subscribe configuration */ { janus_config_item *topic_item = janus_config_get_item_drilldown(config, "admin", "subscribe_topic"); if(!topic_item || !topic_item->value) { JANUS_LOG(LOG_FATAL, "Missing topic for incoming admin messages for MQTT integration...\n"); goto error; } ctx->admin.subscribe.topic = g_strdup(topic_item->value); janus_config_item *qos_item = janus_config_get_item_drilldown(config, "admin", "subscribe_qos"); ctx->admin.subscribe.qos = (qos_item && qos_item->value) ? atoi(qos_item->value) : 1; } /* Admin publish configuration */ { janus_config_item *topic_item = janus_config_get_item_drilldown(config, "admin", "publish_topic"); if(!topic_item || !topic_item->value) { JANUS_LOG(LOG_FATAL, "Missing topic for outgoing admin messages for MQTT integration...\n"); goto error; } ctx->admin.publish.topic = g_strdup(topic_item->value); janus_config_item *qos_item = janus_config_get_item_drilldown(config, "admin", "publish_qos"); ctx->admin.publish.qos = (qos_item && qos_item->value) ? atoi(qos_item->value) : 1; } } else { janus_mqtt_admin_api_enabled_ = FALSE; ctx->admin.subscribe.topic = NULL; ctx->admin.publish.topic = NULL; } if(!janus_mqtt_api_enabled_ && !janus_mqtt_admin_api_enabled_) { JANUS_LOG(LOG_WARN, "MQTT support disabled for both Janus and Admin API, giving up\n"); goto error; } /* Creating a client */ if(MQTTAsync_create( &ctx->client, url, client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL) != MQTTASYNC_SUCCESS) { JANUS_LOG(LOG_FATAL, "Can't connect to MQTT broker: error creating client...\n"); goto error; } if(MQTTAsync_setCallbacks( ctx->client, ctx, janus_mqtt_client_connection_lost, janus_mqtt_client_message_arrived, janus_mqtt_client_delivery_complete) != MQTTASYNC_SUCCESS) { JANUS_LOG(LOG_FATAL, "Can't connect to MQTT broker: error setting up callbacks...\n"); goto error; } /* Connecting to the broker */ int rc = janus_mqtt_client_connect(ctx); if(rc != MQTTASYNC_SUCCESS) { JANUS_LOG(LOG_FATAL, "Can't connect to MQTT broker, return code: %d\n", rc); goto error; } return 0; error: /* If we got here, something went wrong */ janus_transport_session_destroy(mqtt_session); janus_mqtt_client_destroy_context(&ctx); g_free((char *)url); g_free((char *)client_id); g_free(config); return -1; }
/********************************************************************* Test3: More than one client object - simultaneous working. *********************************************************************/ int test3(struct Options options) { #define num_clients 10 int subsqos = 2; MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer; MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer; int rc = 0; int i; client_data clientdata[num_clients]; test_finished = 0; MyLog(LOGA_INFO, "Starting test 3 - multiple connections"); fprintf(xml, "<testcase classname=\"test4\" name=\"multiple connections\""); global_start_time = start_clock(); for (i = 0; i < num_clients; ++i) { sprintf(clientdata[i].clientid, "async_test3_num_%d", i); sprintf(clientdata[i].test_topic, "async test3 topic num %d", i); clientdata[i].index = i; clientdata[i].message_count = 0; rc = MQTTAsync_create(&(clientdata[i].c), options.connection, clientdata[i].clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL); assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc); rc = MQTTAsync_setCallbacks(clientdata[i].c, &clientdata[i], NULL, test3_messageArrived, NULL); assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); opts.keepAliveInterval = 20; opts.cleansession = 1; opts.username = "******"; opts.password = "******"; opts.MQTTVersion = options.MQTTVersion; opts.will = &wopts; opts.will->message = "will message"; opts.will->qos = 1; opts.will->retained = 0; opts.will->topicName = "will topic"; opts.onSuccess = test3_onConnect; opts.onFailure = test3_onFailure; opts.context = &clientdata[i]; MyLog(LOGA_DEBUG, "Connecting"); rc = MQTTAsync_connect(clientdata[i].c, &opts); assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); } while (test_finished < num_clients) { MyLog(LOGA_DEBUG, "num_clients %d test_finished %d\n", num_clients, test_finished); #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif } MyLog(LOGA_DEBUG, "TEST3: destroying clients"); for (i = 0; i < num_clients; ++i) MQTTAsync_destroy(&clientdata[i].c); //exit: MyLog(LOGA_INFO, "TEST3: test %s. %d tests run, %d failures.", (failures == 0) ? "passed" : "failed", tests, failures); write_test_result(); return failures; }
/** * @brief create mqtt * @param[in] host the hostname or ip address of the broker to connect to. * @param[in] port the network port to connect to. Usually 1883. * @param[in] keepalive the number of seconds after which the broker should send a PING message to the client if no other messages have been exchanged in that time. * @param[in] userName authentication user name * @param[in] password authentication password * @param[in] enableServerCertAuth True/False option to enable verification of the server certificate * @param[in] subscribeTopic mqtt topic * @param[in] subscribeTopicSize mqtt topic size * @param[in] publishTopic publish topic * @param[in] enabledCipherSuites cipher format. If this setting is ommitted, its default value will be "ALL". * @param[in] cleanSession if cleanSession=true, then the previous session information is cleared. * @param[in] clientID The client identifier(no longer 23 characters). * @return the return code of the connection response */ int MQTTAsyncCreate(char* host, int port, int keepalive, char* userName, char* password, int enableServerCertAuth, char* subscribeTopic[], int subscribeTopicSize, char* publishTopic, char* enabledCipherSuites, int cleanSession, char* clientID) { #ifdef SPT_DEBUG_ENABLE SPTekDebugLog(LOG_LEVEL_INFO, "MQTTAsyncCreate()"); #else SKTDebugPrint(LOG_LEVEL_INFO, "MQTTAsyncCreate()"); #endif MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_SSLOptions ssl_opts = MQTTAsync_SSLOptions_initializer; int rc; int i = 0; int hostLength = strlen(host); int serverLength = hostLength + 10; int portLength = 5; char server[serverLength]; char pt[portLength]; memset(server, 0, serverLength); memset(pt, 0, portLength); snprintf(pt, portLength, "%d", port); memcpy(server, host, strlen(host)); if(port > 0) { memcpy(server + hostLength, ":", 1); memcpy(server + hostLength + 1, pt, strlen(pt)); } MQTTAsync_create(&mClient, server, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL); conn_opts.keepAliveInterval = keepalive; conn_opts.cleansession = cleanSession; conn_opts.automaticReconnect = 1; conn_opts.onSuccess = OnConnect; conn_opts.onFailure = OnConnectFailure; conn_opts.context = mClient; conn_opts.ssl = &ssl_opts; if(userName) { memset(mUserName, 0, sizeof(mUserName)); memcpy(mUserName, userName, strlen(userName)); conn_opts.username = mUserName; } if(password) { memset(mUserPass, 0, sizeof(mUserPass)); memcpy(mUserPass, password, strlen(password)); conn_opts.password = mUserPass; } ssl_opts.enableServerCertAuth = enableServerCertAuth; mSubscribeTopicsize = subscribeTopicSize; for(i = 0; i < subscribeTopicSize; i++) { memset(mSubscribeTopic[i], 0, sizeof(mSubscribeTopic[i])); strncpy(mSubscribeTopic[i], subscribeTopic[i], strlen(subscribeTopic[i])); } memset(mPublishTopic, 0, sizeof(mPublishTopic)); memcpy(mPublishTopic, publishTopic, strlen(publishTopic)); #ifdef SPT_DEBUG_ENABLE SPTekDebugLog(LOG_LEVEL_INFO, "MQTTAsyncCreate() publish topic : %s", publishTopic); #else SKTDebugPrint(LOG_LEVEL_INFO, "MQTTAsyncCreate() publish topic : %s", publishTopic); #endif MQTTAsync_setCallbacks(mClient, NULL, ConnectionLostCallback, MessageArrivedCallback, MessageDeliveredCallback); if ((rc = MQTTAsync_connect(mClient, &conn_opts)) != MQTTASYNC_SUCCESS){ MQTTAsyncDestroy(); return rc; } return rc; }
/******************************************************************** Test6: HA connections *********************************************************************/ int test6(struct Options options) { int subsqos = 2; test6_client_info cinfo; MQTTAsync_connectOptions opts = MQTTAsync_connectOptions_initializer; MQTTAsync_willOptions wopts = MQTTAsync_willOptions_initializer; int rc = 0; char* test_topic = "C client test1"; char* uris[2] = {options.connection, options.connection}; failures = 0; MyLog(LOGA_INFO, "Starting test 7 - HA connections"); fprintf(xml, "<testcase classname=\"test4\" name=\"HA connections\""); global_start_time = start_clock(); test_finished = 0; cinfo.should_fail = 1; /* fail to connect */ rc = MQTTAsync_create(&cinfo.c, "tcp://rubbish:1883", "async ha connection", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL); assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc); if (rc != MQTTASYNC_SUCCESS) { MQTTAsync_destroy(&cinfo.c); goto exit; } rc = MQTTAsync_setCallbacks(cinfo.c, cinfo.c, NULL, test1_messageArrived, NULL); assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); opts.onSuccess = test6_onConnect; opts.onFailure = test6_onConnectFailure; opts.context = &cinfo; opts.MQTTVersion = options.MQTTVersion; MyLog(LOGA_DEBUG, "Connecting"); rc = MQTTAsync_connect(cinfo.c, &opts); rc = 0; assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); if (rc != MQTTASYNC_SUCCESS) goto exit; while (!test_finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif test_finished = 0; cinfo.should_fail = 0; /* should connect */ rc = MQTTAsync_create(&cinfo.c, "tcp://rubbish:1883", "async ha connection", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL); assert("good rc from create", rc == MQTTASYNC_SUCCESS, "rc was %d\n", rc); if (rc != MQTTASYNC_SUCCESS) { MQTTAsync_destroy(&cinfo.c); goto exit; } rc = MQTTAsync_setCallbacks(cinfo.c, cinfo.c, NULL, test1_messageArrived, NULL); assert("Good rc from setCallbacks", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); opts.onSuccess = test6_onConnect; opts.onFailure = test6_onConnectFailure; opts.context = &cinfo; opts.serverURIs = uris; opts.serverURIcount = 2; MyLog(LOGA_DEBUG, "Connecting"); rc = MQTTAsync_connect(cinfo.c, &opts); rc = 0; assert("Good rc from connect", rc == MQTTASYNC_SUCCESS, "rc was %d", rc); if (rc != MQTTASYNC_SUCCESS) goto exit; while (!test_finished) #if defined(WIN32) Sleep(100); #else usleep(10000L); #endif MQTTAsync_destroy(&cinfo.c); exit: MyLog(LOGA_INFO, "TEST6: test %s. %d tests run, %d failures.", (failures == 0) ? "passed" : "failed", tests, failures); write_test_result(); return failures; }