类本体
4.3.0
csharp
public class MQTTMain
{
public MqttClient mqttClient =null ;
public bool MQTTMainConnect(string MenZuNo, string ServerIP, int ServerPort, string UserName, string Pwd)
{
try
{
string EMQX_CLIENT_ID = $"称重端-{MenZuNo}-{OPCommon.PCControl.GetPCInfos.GetMachineName()}";
mqttClient = new MqttClient(ServerIP, ServerPort, false, null, null, MqttSslProtocols.None);
mqttClient.Connect(EMQX_CLIENT_ID, UserName, Pwd);//需要录入账号密码
return true;
}
catch (Exception ex)
{
OPCommon.LogWrite.WriteLog("MQTT链接错误,信息是:"+ex.Message);
return false;
}
}
/// <summary>
/// 发布主题
/// </summary>
/// <param name="MenZuNo"></param>
/// <param name="ServerIP"></param>
/// <param name="ServerPort"></param>
/// <param name="UserName"></param>
/// <param name="Pwd"></param>
/// <returns></returns>
public bool MQTTMainPublish(string Zhuti, string MsgInfo )
{
try
{
mqttClient.Publish(Zhuti, System.Text.Encoding.UTF8.GetBytes(MsgInfo), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, false);
return true;
}
catch (Exception ex)
{
OPCommon.LogWrite.WriteLog("MQTT发送错误,信息是:" + ex.Message);
return false;
}
}
连接的应用
csharp
/// <summary>
/// MQTT链接重新连接
/// </summary>
public void ThisMQTTConntect()
{
if (ThisMQTTS.mqttClient == null || !ThisMQTTS.mqttClient.IsConnected)
{
ThisMQTTS.MQTTMainConnect(GModel.MainSetupAll.BangNo, GModel.MainSetupAll.ServerIp, GModel.MainSetupAll.ServerPort, GModel.MainSetupAll.ServerUser, GModel.MainSetupAll.Pwd);
}
if (ThisMQTTS.mqttClient != null && ThisMQTTS.mqttClient.IsConnected)
{
ThisMQTTS.mqttClient.MqttMsgPublishReceived += Client_MqttMsgPublishReceived;
ThisMQTTS.mqttClient.ConnectionClosed += TryReconnectAsync;
ThisMQTTS.mqttClient.Subscribe(new string[] { GModel.DingyueZhuti }, new byte[] { MqttMsgBase.QOS_LEVEL_AT_MOST_ONCE });//订阅主题
}
}
断开重连:
csharp
private void TryReconnectAsync(object sender, EventArgs ex)
{
if (!ThisMQTTS.mqttClient.IsConnected && !IsThisClose)
{
OPCommon.LogWrite.WriteLog($"{this.Name}当前断开");
Thread.Sleep(2000);
Thread retryThread = new Thread(new ThreadStart(delegate
{
OPCommon.LogWrite.WriteLog($"{this.Name}第一次重连");
ThisMQTTConntect();
if (!ThisMQTTS.mqttClient.IsConnected)
{
OPCommon.LogWrite.WriteLog($"{this.Name}第二次重连!");
Thread.Sleep(5000);
ThisMQTTConntect();
}
else
{
OPCommon.LogWrite.WriteLog($"{this.Name}第一次重连成功!");
}
}));
retryThread.Start();
}
}
MQTT数据接受
csharp
/// <summary>
/// MQTT操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
//string topic = e.Topic.ToString();//主题内容
string MsgFromMQTT = System.Text.Encoding.UTF8.GetString(e.Message);//数据内容
}
发送数据
csharp
if (ThisMQTTS.mqttClient != null && ThisMQTTS.mqttClient.IsConnected)
{
ThisMQTTS.MQTTMainPublish(GModel.DingyueZhuti, SetToServer);
OPCommon.LogWrite.WriteLog("数据发送成功:" + SetToServer);
ChengzhongMainWath.Restart();
}