コード例 #1
0
ファイル: pubasync.c プロジェクト: Adamwuming/paho.mqtt.c
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;

    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

    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;
    deliveredtoken = 0;
    MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
    printf("Waiting for publication of %s\n"
            "on topic %s for client with ClientID: %s\n",
            PAYLOAD, TOPIC, CLIENTID);
    while(deliveredtoken != token);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
コード例 #2
0
ファイル: mqtt-client.c プロジェクト: TeamElevate/edison
/**
 * @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;
}
コード例 #3
0
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);
}
コード例 #4
0
ファイル: ConMQTT.cpp プロジェクト: tuttitan/2016-camp
bool CConMQTT::bPublishMessage(char cCorner, int iDir)
{
	// 局所変数宣言
	int iRet;             // 関数呼出しの戻り値
	char szTopic[31];     // トピック名
	char szMsg[31];       // メッセージペイロード
	MQTTClient_message stMsg = MQTTClient_message_initializer;     // メッセージ

	// トピックの決定
	sprintf_s(szTopic, "%s/%c", TOPIC, cCorner);

	// メッセージの決定
	_itoa_s(iDir, szMsg, 10);
	stMsg.payload = szMsg;
	stMsg.payloadlen = strlen(szMsg);
	stMsg.qos = QOS;
	stMsg.retained = 0;

	iRet = MQTTClient_publishMessage(m_Client, szTopic, &stMsg, (MQTTClient_deliveryToken*)&s_DeliveredToken);
	if (MQTTCLIENT_SUCCESS != iRet) {
		return false;
	}

	return true;
}
コード例 #5
0
ファイル: test3.c プロジェクト: Adamwuming/paho.mqtt.c
/*********************************************************************

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);
	}
}
コード例 #6
0
ファイル: clpi.c プロジェクト: krattai/noo-ebs
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;
}
コード例 #7
0
ファイル: mqtt.c プロジェクト: tok101/tok101
int mqtt_publish_message(MQTTClient client, const char* topic,const char* message, int qos)
{
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    pubmsg.payload = (void*)message;
    pubmsg.payloadlen = strlen(message);
    pubmsg.qos = qos;
    pubmsg.retained = 0;
    return MQTTClient_publishMessage(client, topic, &pubmsg, &token);
}
コード例 #8
0
ファイル: util.c プロジェクト: iamjkp/ESW1-Project
int mqtt_pub(MQTTClient *context, char *payload, char *topic, int qos) {
	int rc = 0;
	MQTTClient_message pubmsg = MQTTClient_message_initializer;
	MQTTClient_deliveryToken token;
	pubmsg.payload = payload;
	pubmsg.payloadlen = strlen(payload);
	pubmsg.qos = qos;
	pubmsg.retained = 0;
	MQTTClient_publishMessage(*context, topic, &pubmsg, &token);
	return rc;
}
コード例 #9
0
// [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;
}
コード例 #10
0
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);
}
コード例 #11
0
ファイル: mqttclient_module.c プロジェクト: CJxD/paho.mqtt.c
static PyObject* mqttv3_publishMessage(PyObject* self, PyObject *args)
{
	MQTTClient c;
	char* topicName;
	PyObject *message, *temp;
	MQTTClient_message msg = MQTTClient_message_initializer;
	MQTTClient_deliveryToken dt;
	int rc;

	if (!PyArg_ParseTuple(args, "ksO", &c, &topicName, &message))
		return NULL;

	if (!PyDict_Check(message))
	{
		PyErr_SetString(PyExc_TypeError, "3rd parameter must be a dictionary");
		return NULL;
	}

	if ((temp = PyDict_GetItemString(message, "payload")) == NULL)
	{
		PyErr_SetString(PyExc_TypeError, "dictionary must have payload key");
		return NULL;
	}

	if (PyString_Check(temp))
		PyString_AsStringAndSize(temp, (char**) &msg.payload,
				(Py_ssize_t*) &msg.payloadlen);
	else
	{
		PyErr_SetString(PyExc_TypeError, "payload value must be string");
		return NULL;
	}

	if ((temp = PyDict_GetItemString(message, "qos")) == NULL)
		msg.qos = (int) PyInt_AsLong(temp);

	if ((temp = PyDict_GetItemString(message, "retained")) == NULL)
		msg.retained = (int) PyInt_AsLong(temp);

	Py_BEGIN_ALLOW_THREADS rc = MQTTClient_publishMessage(c, topicName, &msg,
			&dt);
	Py_END_ALLOW_THREADS

	if (rc == MQTTCLIENT_SUCCESS && msg.qos > 0)
		return Py_BuildValue("ii", rc, dt);
	else
		return Py_BuildValue("i", rc);
}
コード例 #12
0
ファイル: MQTT.cpp プロジェクト: MartinHaimberger/Homegear
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__);
	}
}
コード例 #13
0
ファイル: nmain.c プロジェクト: vaibhav1233/mqtt
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;
}
コード例 #14
0
int main(int argc, char* argv[])
{
    if(argc < 4) {
        std::cout << "usage: " << argv[0] << " server_url user password" << std::endl;
        return -1;
    }

    std::cout << argv[0] << " " << argv[1] << " " << argv[2] << " " << argv[3] << std::endl;


    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    int rc;
    MQTTClient_create(&client, argv[1], CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.username = argv[2];
    conn_opts.password = argv[3];
    conn_opts.connectTimeout = 200;


    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);
    }
    pubmsg.payload = const_cast<char*>(PAYLOAD);
    pubmsg.payloadlen = strlen(PAYLOAD);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    deliveredtoken = 0;
    MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
    printf("Waiting for publication of %s\n"
           "on topic %s for client with ClientID: %s\n",
           PAYLOAD, TOPIC, CLIENTID);
    while(deliveredtoken != token);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
コード例 #15
0
ファイル: test3.c プロジェクト: Adamwuming/paho.mqtt.c
void multiThread_sendAndReceive(MQTTClient* c, int qos, char* test_topic)
{
	MQTTClient_deliveryToken dt;
	int i = 0;
	int iterations = 50;
	int rc = 0;
	int wait_seconds = 0;

	multiThread_deliveryCompleted = 0;
	multiThread_arrivedcount = 0;

	MyLog(LOGA_DEBUG, "%d messages at QoS %d", iterations, qos);
	multiThread_pubmsg.payload = "a much longer message that we can shorten to the extent that we need to";
	multiThread_pubmsg.payloadlen = 27;
	multiThread_pubmsg.qos = qos;
	multiThread_pubmsg.retained = 0;

	for (i = 1; i <= iterations; ++i)
	{
		if (i % 10 == 0)
			rc = MQTTClient_publish(c, test_topic, multiThread_pubmsg.payloadlen, multiThread_pubmsg.payload, 
                   multiThread_pubmsg.qos, multiThread_pubmsg.retained, NULL);
		else
			rc = MQTTClient_publishMessage(c, test_topic, &multiThread_pubmsg, &dt);
		assert("Good rc from publish", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);

		#if defined(WIN32)
			Sleep(100);
		#else
			usleep(100000L);
		#endif

		wait_seconds = 20;
		while ((multiThread_arrivedcount < i) && (wait_seconds-- > 0))
		{
			MyLog(LOGA_DEBUG, "Arrived %d count %d", multiThread_arrivedcount, i);
			#if defined(WIN32)
				Sleep(1000);
			#else
				usleep(1000000L);
			#endif
		}
		assert("Message Arrived", wait_seconds > 0, 
				"Time out waiting for message %d\n", i );
	}
	if (qos > 0)
	{
		/* MQ Telemetry can send a message to a subscriber before the server has
		   completed the QoS 2 handshake with the publisher. For QoS 1 and 2,
		   allow time for the final delivery complete callback before checking
		   that all expected callbacks have been made */ 
		wait_seconds = 10;
		while ((multiThread_deliveryCompleted < iterations) && (wait_seconds-- > 0))
		{
			MyLog(LOGA_DEBUG, "Delivery Completed %d count %d", multiThread_deliveryCompleted, i);
			#if defined(WIN32)
				Sleep(1000);
			#else
				usleep(1000000L);
			#endif
		}
		assert("All Deliveries Complete", wait_seconds > 0, 
			   "Number of deliveryCompleted callbacks was %d\n", 
			   multiThread_deliveryCompleted);
	}
}
コード例 #16
0
ファイル: mqttapi_paho.c プロジェクト: neo7206/azure-iot-sdks
void MQTTAPI_DoWork(MQTTAPI_HANDLE instance)
{
	PMQTTTAPI_HANDLE_DATA handle = instance;

	/* Codes_SRS_MQTTAPI_04_050: [if parameter instance is NULL then MQTTAPI_DoWork shall not perform any action.] */
	if (handle != NULL)
	{

		if (!checkAndTryToConnect(handle))
		{
			LogError("Client Not Connected and could not connect.\r\n");
		}
		else
		{
			if (Lock(handle->LockHandle) == LOCK_OK)
			{

				//message
				{
					PDLIST_ENTRY received;
					while ((received = DList_RemoveHeadList(&(handle->messagesReceived))) != &(handle->messagesReceived))
					{
						MQTTAPI_MESSAGE_RECEIVED_LIST* temp = containingRecord(received, MQTTAPI_MESSAGE_RECEIVED_LIST, entry);
						if (handle->maCallBack != NULL)
						{
							if (!handle->maCallBack(handle->maCallbackContext, temp->messageReceived))
							{
								LogError("Client could not handle message, dropping it.");
							}
						}

						free(temp->messageReceived->payload);
						free(temp->messageReceived);
						free(temp);
					}
				}
				Unlock(handle->LockHandle);
			}
			else
			{
				LogError("Could not aquire lock for message.\r\n");
			}

			//Event
			{
				PDLIST_ENTRY messageToSend;
				while ((messageToSend = DList_RemoveHeadList(&(handle->messagesToSend))) != &(handle->messagesToSend))
				{
					MQTTAPI_MESSAGE_SEND_LIST* temp = containingRecord(messageToSend, MQTTAPI_MESSAGE_SEND_LIST, entry);

					if (MQTTClient_publishMessage(handle->client, STRING_c_str(temp->topicName), temp->messageToSend, &(temp->dt)) != MQTTCLIENT_SUCCESS)
					{
						handle->dcCallback(temp->context, MQTTAPI_CONFIRMATION_ERROR);
						MQTTClient_freeMessage(&(temp->messageToSend));
						free(temp->messageToSend);
						STRING_delete(temp->topicName);
						free(temp);
					}
					else
					{
						DList_InsertTailList(&(handle->messagesSent), &(temp->entry));
					}
				}
			}
		}
	}
	
}
コード例 #17
0
ファイル: pub.c プロジェクト: liupengfei06/Dotlink-C-SDK
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;
}