void log_mqtt(std::string payload) { if (!getenv("MQTT_SERVER")) { return; } init_mqtt(); int rc; if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { std::cout << "Failed to connect to MQTT server, return code:" << rc << std::endl; return; } std::stringstream json; json << "{\"d\": " << payload << " }"; std::string jsonStr = json.str(); pubmsg.payload = &jsonStr; pubmsg.payloadlen = json.str().length(); pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage(client, getenv("MQTT_TOPIC"), &pubmsg, &token); std::cout << "Publishing to MQTT server on" << getenv("MQTT_TOPIC") << std::endl; std::cout << json.str() << std::endl; rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); std::cout << "MQTT message delivered" << std::endl; MQTTClient_disconnect(client, 10000); }
/********************************************************************* Test: single-threaded client *********************************************************************/ void singleThread_sendAndReceive(MQTTClient* c, int qos, char* test_topic) { MQTTClient_deliveryToken dt; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_message* m = NULL; char* topicName = NULL; int topicLen; int i = 0; int iterations = 50; int rc; MyLog(LOGA_DEBUG, "%d messages at QoS %d", iterations, qos); pubmsg.payload = "a much longer message that we can shorten to the extent that we need to payload up to 11"; pubmsg.payloadlen = 11; pubmsg.qos = qos; pubmsg.retained = 0; for (i = 0; i< iterations; ++i) { if (i % 10 == 0) rc = MQTTClient_publish(c, test_topic, pubmsg.payloadlen, pubmsg.payload, pubmsg.qos, pubmsg.retained, NULL); else rc = MQTTClient_publishMessage(c, test_topic, &pubmsg, &dt); assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc); if (qos > 0) { rc = MQTTClient_waitForCompletion(c, dt, 20000L); assert("Good rc from waitforCompletion", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc); } rc = MQTTClient_receive(c, &topicName, &topicLen, &m, 10000); assert("Good rc from receive", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc); if (topicName) { MyLog(LOGA_DEBUG, "Message received on topic %s is %.*s", topicName, m->payloadlen, (char*)(m->payload)); if (pubmsg.payloadlen != m->payloadlen || memcmp(m->payload, pubmsg.payload, m->payloadlen) != 0) { failures++; MyLog(LOGA_INFO, "Error: wrong data - received lengths %d %d", pubmsg.payloadlen, m->payloadlen); break; } MQTTClient_free(topicName); MQTTClient_freeMessage(&m); } else printf("No message received within timeout period\n"); } /* receive any outstanding messages */ MQTTClient_receive(c, &topicName, &topicLen, &m, 1000); while (topicName) { printf("Message received on topic %s is %.*s.\n", topicName, m->payloadlen, (char*)(m->payload)); MQTTClient_free(topicName); MQTTClient_freeMessage(&m); MQTTClient_receive(c, &topicName, &topicLen, &m, 1000); } }
int main(int argc, char* argv[]) { MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; int rc; MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { printf("Failed to connect, return code %d\n", rc); exit(-1); } pubmsg.payload = PAYLOAD; pubmsg.payloadlen = strlen(PAYLOAD); pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token); printf("Waiting for up to %d seconds for publication of %s\n" "on topic %s for client with ClientID: %s\n", (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID); rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); printf("Message with delivery token %d delivered\n", token); MQTTClient_disconnect(client, 10000); MQTTClient_destroy(&client); return rc; }
/** * @name Publish a message * @brief Used to send message to a broker. * @param[in] message to be published * @param[in] context w.r.t topic the message required to be published * @return boolean, specifies whether the message is successfully published or not */ int send(char *message, Context context) { MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; int rc = 0; char *topic; if (context.name != NULL && context.value != NULL && strcmp(context.name, "topic") == 0) { topic = context.value; } else { printf("Topic not available in the send command"); return MQTTCLIENT_NULL_PARAMETER; } pubmsg.payload = message; pubmsg.payloadlen = strlen(message); pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage(client, topic, &pubmsg, &token); #if DEBUG printf("Waiting for up to %d seconds for publication of %s\n" "on topic %s for client with ClientID: %s\n", (int)(TIMEOUT/1000), message, topic, clientID); #endif rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); #if DEBUG printf("Message with delivery token %d delivered\n", token); #endif return rc; }
// [START iot_mqtt_publish] int Publish(char* payload, int payload_size) { int rc = -1; MQTTClient client = {0}; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token = {0}; MQTTClient_create(&client, opts.address, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.username = kUsername; conn_opts.password = CreateJwt(opts.ecpath, opts.projectid); MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer; sslopts.trustStore = opts.rootpath; sslopts.privateKey = opts.ecpath; conn_opts.ssl = &sslopts; unsigned long retry_interval_ms = kInitialConnectIntervalMillis; unsigned long total_retry_time_ms = 0; while ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { if (rc == 3) { // connection refused: server unavailable usleep(retry_interval_ms / 1000); total_retry_time_ms += retry_interval_ms; if (total_retry_time_ms >= kMaxConnectRetryTimeElapsedMillis) { printf("Failed to connect, maximum retry time exceeded."); exit(EXIT_FAILURE); } retry_interval_ms *= kIntervalMultiplier; if (retry_interval_ms > kMaxConnectIntervalMillis) { retry_interval_ms = kMaxConnectIntervalMillis; } } else { printf("Failed to connect, return code %d\n", rc); exit(EXIT_FAILURE); } } pubmsg.payload = payload; pubmsg.payloadlen = payload_size; pubmsg.qos = kQos; pubmsg.retained = 0; MQTTClient_publishMessage(client, opts.topic, &pubmsg, &token); printf("Waiting for up to %lu seconds for publication of %s\n" "on topic %s for client with ClientID: %s\n", (kTimeout/1000), opts.payload, opts.topic, opts.clientid); rc = MQTTClient_waitForCompletion(client, token, kTimeout); printf("Message with delivery token %d delivered\n", token); MQTTClient_disconnect(client, 10000); MQTTClient_destroy(&client); return rc; }
void log_mqtt(std::string payload) { if (!getenv("MQTT_SERVER")) { return; } MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; int rc; MQTTClient_create(&client, getenv("MQTT_SERVER"), getenv("MQTT_CLIENTID"), MQTTCLIENT_PERSISTENCE_NONE, NULL); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; conn_opts.username = getenv("MQTT_USERNAME"); conn_opts.password = getenv("MQTT_PASSWORD"); MQTTClient_SSLOptions sslOptions = MQTTClient_SSLOptions_initializer; if (getenv("MQTT_CERT") && getenv("MQTT_KEY") && getenv("MQTT_CA")) { sslOptions.keyStore = getenv("MQTT_CERT"); sslOptions.privateKey = getenv("MQTT_KEY"); sslOptions.trustStore = getenv("MQTT_CA"); } else { sslOptions.enableServerCertAuth = false; }; conn_opts.ssl = &sslOptions; if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { std::cout << "Failed to connect to MQTT server, return code:" << rc << std::endl; return; } std::stringstream json; json << "{\"d\": " << payload << " }"; std::string jsonStr = json.str(); pubmsg.payload = &jsonStr; pubmsg.payloadlen = json.str().length(); pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage(client, getenv("MQTT_TOPIC"), &pubmsg, &token); std::cout << "Publishing to MQTT server on" << getenv("MQTT_TOPIC") << std::endl; std::cout << json.str() << std::endl; rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); std::cout << "MQTT message delivered" << std::endl; MQTTClient_disconnect(client, 10000); MQTTClient_destroy(&client); }
static PyObject* mqttv3_waitForCompletion(PyObject* self, PyObject *args) { MQTTClient c; unsigned long timeout = 1000L; MQTTClient_deliveryToken dt; int rc; if (!PyArg_ParseTuple(args, "ki|i", &c, &dt, &timeout)) return NULL; Py_BEGIN_ALLOW_THREADS rc = MQTTClient_waitForCompletion(c, dt, timeout); Py_END_ALLOW_THREADS return Py_BuildValue("i", rc); }
void MQTT::publish(const std::string& topic, const std::vector<char>& data) { try { if(data.empty()) return; std::string fullTopic = "homegear/" + _settings.homegearId() + "/" + topic; for(int32_t i = 0; i < 3; i++) { if(_client == nullptr) connect(); if(_client == nullptr) { GD::out.printError("Could not publish message, because we are not connected to a message broker. Topic: " + fullTopic + " Data: " + std::string(&data.at(0), data.size())); return; } MQTTClient_deliveryToken token; MQTTClient_message message = MQTTClient_message_initializer; message.payload = (void*)&data.at(0); message.payloadlen = data.size(); message.qos = 1; message.retained = 0; if(GD::bl->debugLevel >= 5) _out.printDebug("Publishing message with topic " + fullTopic + ": " + std::string(&data.at(0), data.size())); MQTTClient_publishMessage(_client, fullTopic.c_str(), &message, &token); if(MQTTClient_waitForCompletion(_client, token, 5000) != MQTTCLIENT_SUCCESS) { if(i == 2) GD::out.printError("Could not publish message with topic " + fullTopic + " and data: " + std::string(&data.at(0), data.size())); disconnect(); continue; } break; } } catch(const std::exception& ex) { _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } catch(BaseLib::Exception& ex) { _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what()); } catch(...) { _out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__); } }
int publish(int payloadLen, char *payload) { int ret; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; pubmsg.payload = payload; pubmsg.payloadlen = payloadLen; pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token); printf("Waiting for up to %d seconds for publication of %s\n" "on topic %s for client with ClientID: %s\n", (int)(TIMEOUT/1000), payload, TOPIC, CLIENTID); ret = MQTTClient_waitForCompletion(client, token, TIMEOUT); printf("Message with delivery token %d delivered\n", token); return ret; }
/* * Update the temperature values and send the values to IBM Bluemix * - blink the led to show the temperature was measured and data updated */ void temperature_update(upm::GroveTemp* temperature_sensor, upm::GroveLed* led) { // other helper variables int temperature; // temperature sensor value in degrees Celsius std::stringstream row_1; // temperature // update temperature values temperature = temperature_sensor->value(); // convert the message into JSON format row_1 << "{ \"temp\": \"" << temperature << "\" }"; // send message to IBM Bluemix char payload[80]; sprintf(payload, "{ \"temp\": \"%d\" }", temperature); int payloadlen = strlen(payload); int retained = 0; MQTTClient_deliveryToken dt; int rc = MQTTClient_publish(client, const_cast<char *>(topic), payloadlen, const_cast<char *>(payload), MQTT_DEFAULT_QOS, retained, &dt); if (rc == MQTTCLIENT_SUCCESS) { printf("Waiting for message with token %d to be published...\n", dt); rc = MQTTClient_waitForCompletion(client, dt, 1000); if (rc == MQTTCLIENT_SUCCESS) { printf("Message with token %d published\n", dt); } else { std::cerr << "Failed to publish message with token " << dt << std::endl; } } else { std::cerr << "Failed to publish message with token " << dt << std::endl; } // blink the led for 50 ms to show the temperature was actually sampled led->on(); usleep(50000); led->off(); }
// ------------------------------------------------------------------- // !!!!!!!!!!! FONCTION DEBUG A RETRAVAILLER... // ------------------------------------------------------------------- int algo_putMessage(char *topic, char *data, unsigned short lenght){ short j; int rc; unsigned short crc16=0; // Generation du CRC du message for(j=0;j < lenght;j++){ crc16=update_crc_16(crc16, data[j]); } // Ajout du CRC dans la trame data[lenght++]=(crc16&0xFF00)>>8; data[lenght++]=(crc16&0x00FF); // Publication du message //printf("\n PUBLICATION: "); //for(i=0;i<lenght; i++) printf(" %x", data[i]); MQTTClient_publish(client, topic, lenght, data, QOS, 0, &token); rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); return (rc); }
int main(int argc, char* argv[]) { MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; int rc; char *pid = "b1e57467c92140e299022deb808cdd24"; //产品唯一标识 char *productSecret = "2c15e161b5064d32ba6a6f664fbcde15"; //密钥 char *did = "111111"; //设备ID //1.发送HTTP请求,获取用于创建MQTT连接使用的clientId, username, password, host. int res = MQTTClient_setup_with_pid_and_did(pid, did, productSecret, &my_PRO_info); if (res < 0) { printf("can't get product info\n"); return 0; } printf("Get product info: client_id:%s,username:%s,password:%s, host:%s\n", my_PRO_info.client_id, my_PRO_info.username, my_PRO_info.password, my_PRO_info.host); //2.创建MQTT连接:测试时发送端和接收端不能是同一clientId,两边如果相同,会判断是同一设备而收不到消息 MQTTClient_create(&client, my_PRO_info.host, my_PRO_info.client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL); conn_opts.keepAliveInterval = 20; conn_opts.reliable = 1; conn_opts.cleansession = 1; conn_opts.password=my_PRO_info.password; conn_opts.username=my_PRO_info.username; //3.连接MQTT:返回值为0时,连接成功 if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { printf("Failed to connect, return code %d\n", rc); exit(-1); } // rc = MQTTClient_subscribe(client, TOPIC, 1); int order_id=525121535; int msgid=1; while (isContinue) { int code=1; char payload[2048]; long payloadLen; int did2=2554612; char streams[1024]; char stream[200]="{\"id\": \"switch\",\"value\": \"s\"}"; //开关指令 // char stream[200]="{\"id\": \"p\",\"value\": \"22:00\"}"; //设置定时 // char stream[200]="{\"id\": \"dis\",\"value\": \"disconnect\"}"; //断开连接指令 sprintf(streams, "["); strcat(streams, stream); strcat(streams, "]"); sprintf(payload,"{\"code\":%d,\"order_id\":%d,\"data_points\":%s,\"did\":%d}",code,order_id,streams,did2); payloadLen =strlen(payload); pubmsg.payload = payload; //publish消息内容 pubmsg.payloadlen = payloadLen; pubmsg.qos = QOS; //三种消息发布服务质量. 0:“至多一次”,消息发布完全依赖底层 TCP/IP 网络。会发生消息丢失或重复。这一级别可用于如下情况,环境传感器数据,丢失一次读记录无所谓,因为不久后还会有第二次发送。1:“至少一次”,确保消息到达,但消息重复可能会发生。2:“只有一次”,确保消息到达一次。这一级别可用于如下情况,在计费系统中,消息重复或丢失会导致不正确的结果。 pubmsg.msgid=msgid; //4.发送消息,payload即为需要发送的消息内容,可以拼成JSON字符串,接收端收到后对它进行解析处理 rc=MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token); if(rc==0){ printf("\n\n"); printf("publish-success:"); for (int i=0; i<payloadLen; i++) { printf("%c",payload[i]); } } rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); order_id++; msgid++; } MQTTClient_disconnect(client, 10000); MQTTClient_destroy(&client); return rc; }