mqtt
//MQTT注册(连接)
bool RegisterMQTT(const std::string& user, const std::string& pwd, const std::string& serviceIp, const std::string& source)
{
int rc = -1;
rc = MQTTAsync_create(&m_client, serviceIp.c_str(), source.c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
if (MQTTASYNC_SUCCESS != rc)
{
return false;
}
rc = MQTTAsync_setCallbacks(m_client, NULL, connlost, msgarrvd, NULL);
if (rc != MQTTASYNC_SUCCESS)
{
return false;
}
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = CMQTTLibrary::onConnect;
conn_opts.onFailure = CMQTTLibrary::onConnectFailure;
conn_opts.context = m_context;
conn_opts.username = user.c_str();//一般为 admin
conn_opts.password = pwd.c_str();//一般为admin
if ((rc = MQTTAsync_connect(m_client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
return false;
}
return true;
}
//MQTT断开连接
bool InterruptMQTT()
{
MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
disc_opts.onSuccess = CMQTTLibrary::onDisconnect;
disc_opts.onFailure = CMQTTLibrary::onConnectFailure;
disc_opts.context = m_context;
int rc;
if ((rc = MQTTAsync_disconnect(m_client, &disc_opts)) != MQTTASYNC_SUCCESS)
{
return false;
}
return true;
}
//MQTT订阅
bool SubscriptionMQTT(const std::string& source)
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = onSubscribe;
opts.onFailure = onSubscribeFailure;
opts.context = m_context;
const char* ptSource = source.c_str();
int rc = -1;
if ((rc = MQTTAsync_subscribe(m_client, ptSource, m_qos, &opts)) != MQTTASYNC_SUCCESS)
{
return false;
}
return true;
}
//MQTT取消订阅
bool CancelSubMQTT()
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = CMQTTLibrary::OnUnSubscribeSuccess;
opts.onFailure = CMQTTLibrary::OnUnSubscribeFail;
opts.context = m_context;
int rc = MQTTAsync_unsubscribe(m_client, m_source.c_str(), &opts);
if (rc != MQTTASYNC_SUCCESS)
{
return false;
}
return true;
}
//发送MQTT消息
bool SendMQTTMsg(const std::string& destid, const std::string& imsg)
{
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
opts.onSuccess = CMQTTLibrary::onSend;
opts.onFailure = CMQTTLibrary::onSendFailure;
opts.context = m_context;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
pubmsg.payload = (void*)imsg.c_str();
pubmsg.payloadlen = imsg.length();
pubmsg.qos = m_qos;
pubmsg.retained = 0;
int rc;
if ((rc = MQTTAsync_sendMessage(m_client, destid.c_str(), &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
return false;
}
return true;
}
//接受消息
int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
{
CListBox *list = (CListBox*)context;
CString strMsg = "收到消息:[";
strMsg += topicName;
strMsg += "]";
strMsg += (char*)message->payload;
}