mqtt first use
The
project involves TCP communication, and the encapsulated MQTT package is implemented under other people’s suggestions.
In the VS NUGET package management, you can find a variety of packets of MQTT. I use version 2.8.2 Mqttnet here
Directly apply code
public async void mqttclient ()
{{
if (! MQTTISCONNECTED)
{{
try
{{
// Configuration
Var options = new mqttclientoptions () {clientid = guid.newguid (). Tostring ("d")};
options.ChannelOptions = New MQTTClienttcpopTIONS ()
{{
Server = "***. ***. ***. ***",
Port = *****
};
options.credentials = New MQTTClientCREDENTIALS ()
{{
Username = "admin",
Password = "password"
};
options.CleAnsulation = TRUE;
options.keepaliveperiod = Timespan.fromseconds (100.5);
options.keepaliveSendinterval = Timespan.fromseconds (20000);
if (null! = _mqttclient)
{{
await_mqttclient.disconnectasync ();
_mqttclient = null;
}
_mqttclient = new mqttfactory (). CreatemqttClient ();
_mqttclient.applicationMessageRecated += (Sender, ARGS) =>
{{
| Retain: {args.applicationmessage.retain} ");
};
_mqttclient.connect += (Sender, ARGS) =>
{{
Debug.log ($ "client is connected: issessionPreres: {args.issessionPreSent}"););
};
_mqttclient.disconnect += (Sender, ARGS) =>
{{
Debug.log ($ "Client is disconnected clientwasconnected: {args.clientWasconnect}");
};
await_mqttclient.connectasync (options);
mqttisconnect = true;
try
{{
await task.factory.startnew (async () =>
{{
await_mqttclient.subscribeasync (
New list <TopicFilter>
{{
New TopicFilter (
"test", // Subscribe theme
(MQTTQUALITYOFSERVILEVEL)
Enum.parse (Typeof (MQTTQUALITYOFSERVILEVEL), "0"))
});
});
}
catch (Exception EX)
{{
Debug.log (ex.MESSAGE);
}
}
catch (Exception EX)
{{
Debug.log (ex.MESSAGE);
}
}
}
Public async void clientstop ()
{{
if (MQTTISCONNECTED)
{{
if (null! = _mqttclient && _mqttclient.isconnect)
{{
await_mqttclient.disconnectasync ();
_mqttclient.dispose ();
_mqttclient = null;
mqttisconnect = false;
Debug.log ("Disconnected");
}
}
}