You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
using System.Text;
|
|
|
|
|
using MQTTnet.Client;
|
|
|
|
|
using MQTTnet.Formatter;
|
|
|
|
|
|
|
|
|
|
namespace Service.Cloud.Client;
|
|
|
|
|
|
|
|
|
|
public class CloudClient
|
|
|
|
|
{
|
|
|
|
|
#region client param
|
|
|
|
|
|
|
|
|
|
public string ServerIp { get; set; }
|
|
|
|
|
public int ServerPort { get; set; }
|
|
|
|
|
public string ClientId { get; set; }
|
|
|
|
|
public string? Username { get; set; }
|
|
|
|
|
public string Password { get; set; }
|
|
|
|
|
public int KeepalivePeriod { get; set; }
|
|
|
|
|
public int Timeout { get; set; }
|
|
|
|
|
public string Version { get; set; }
|
|
|
|
|
public bool IsCleanSession { get; set; }
|
|
|
|
|
|
|
|
|
|
#endregion
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
private MqttClientOptions BuildOptions()
|
|
|
|
|
{
|
|
|
|
|
MqttClientOptionsBuilder builder =
|
|
|
|
|
new MqttClientOptionsBuilder().WithTcpServer(ServerIp, ServerPort).WithClientId(ClientId);
|
|
|
|
|
if (!string.IsNullOrWhiteSpace(Username))
|
|
|
|
|
{
|
|
|
|
|
builder.WithCredentials(Username, Encoding.UTF8.GetBytes(Password));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (IsCleanSession)
|
|
|
|
|
{
|
|
|
|
|
builder.WithCleanSession();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
builder.WithKeepAlivePeriod(TimeSpan.FromSeconds(KeepalivePeriod)).WithTimeout(TimeSpan.FromSeconds(Timeout));
|
|
|
|
|
switch (Version)
|
|
|
|
|
{
|
|
|
|
|
case "3.1.0":
|
|
|
|
|
builder.WithProtocolVersion(MqttProtocolVersion.V310);
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
|
|
case "5.0.16":
|
|
|
|
|
builder.WithProtocolVersion(MqttProtocolVersion.V500);
|
|
|
|
|
break;
|
|
|
|
|
|
|
|
|
|
default:
|
|
|
|
|
builder.WithProtocolVersion(MqttProtocolVersion.V311);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return builder.Build();
|
|
|
|
|
}
|
|
|
|
|
}
|