You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
68 lines
2.4 KiB
C#
68 lines
2.4 KiB
C#
using MQTTnet;
|
|
using MQTTnet.Client;
|
|
using MQTTnet.Protocol;
|
|
|
|
namespace OpenAuth.WebApi;
|
|
|
|
public class MqttClientManager
|
|
{
|
|
private IMqttClient _mqttClient;
|
|
|
|
public MqttClientManager()
|
|
{
|
|
var mqttFactory = new MqttFactory();
|
|
_mqttClient = mqttFactory.CreateMqttClient();
|
|
// 创建配置构建器
|
|
var builder = new ConfigurationBuilder()
|
|
.SetBasePath(Directory.GetCurrentDirectory())
|
|
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
|
|
.AddJsonFile(
|
|
$"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json",
|
|
optional: true)
|
|
.AddEnvironmentVariables();
|
|
// 构建配置
|
|
var configuration = builder.Build();
|
|
// 读取连接字符串
|
|
var serverIp = configuration["MQTT:Server"];
|
|
var port = configuration["MQTT:Port"];
|
|
var username = configuration["MQTT:UserName"];
|
|
var password = configuration["MQTT:Password"];
|
|
ConnectAsync(serverIp, int.Parse(port), username, password).Wait();
|
|
}
|
|
|
|
/// <summary>
|
|
///
|
|
/// </summary>
|
|
/// <param name="server"></param>
|
|
/// <param name="port"></param>
|
|
/// <param name="username"></param>
|
|
/// <param name="password"></param>
|
|
public async Task ConnectAsync(string server, int port, string username = null, string password = null)
|
|
{
|
|
var mqttClientOptions = new MqttClientOptionsBuilder()
|
|
.WithClientId("client001")
|
|
.WithTcpServer(server, port)
|
|
.WithCredentials(username, password)
|
|
.Build();
|
|
|
|
await _mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);
|
|
}
|
|
|
|
public async Task SubscribeAsync(string topic,
|
|
Func<MqttApplicationMessageReceivedEventArgs, Task> handler)
|
|
{
|
|
await _mqttClient.SubscribeAsync(topic, MqttQualityOfServiceLevel.AtLeastOnce, CancellationToken.None);
|
|
_mqttClient.ApplicationMessageReceivedAsync += handler;
|
|
}
|
|
|
|
|
|
public async Task PublishAsync(string topic, string message)
|
|
{
|
|
var mqttMsg = new MqttApplicationMessageBuilder()
|
|
.WithTopic(topic)
|
|
.WithPayload(message)
|
|
.WithQualityOfServiceLevel(MqttQualityOfServiceLevel.AtLeastOnce)
|
|
.Build();
|
|
await _mqttClient.PublishAsync(mqttMsg, CancellationToken.None);
|
|
}
|
|
} |