HYZ.MqttClient
0.0.3
dotnet add package HYZ.MqttClient --version 0.0.3
NuGet\Install-Package HYZ.MqttClient -Version 0.0.3
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="HYZ.MqttClient" Version="0.0.3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="HYZ.MqttClient" Version="0.0.3" />
<PackageReference Include="HYZ.MqttClient" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add HYZ.MqttClient --version 0.0.3
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: HYZ.MqttClient, 0.0.3"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package HYZ.MqttClient@0.0.3
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=HYZ.MqttClient&version=0.0.3
#tool nuget:?package=HYZ.MqttClient&version=0.0.3
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
基于开源MQTTnet封装MqttClient库,适用net8.0,net9.0,net10.0
快速开始 二选一
// 添加Mqtt服务
builder.Services.AddHYZMqttServices(builder.Configuration.GetSection("MqttConfig"));
// 添加Mqtt服务
var mqttConfigOption = builder.Configuration.GetSection("MqttConfig").Get<MqttConfig>() ?? new MqttConfig();
builder.Services.AddHYZMqttServices(mqttConfig =>
{
mqttConfig.Server = mqttConfigOption.Server;
mqttConfig.Port = mqttConfigOption.Port;
mqttConfig.Username = mqttConfigOption.Username;
mqttConfig.Password = mqttConfigOption.Password;
});
如何使用
/// <summary>
/// Mqtt测试
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class MqttTestController : ControllerBase
{
private readonly IMqttClientHelper _mqttClientHelper;
private readonly ILogger<MqttTestController> _logger;
/// <summary>
/// 构造函数
/// </summary>
public MqttTestController(
IMqttClientHelper mqttClientHelper,
ILogger<MqttTestController> logger,)
{
_mqttClientHelper = mqttClientHelper;
_logger = logger;
// 订阅消息接收事件
_mqttClientHelper.MessageReceived += OnMessageReceived;
}
/// <summary>
/// 订阅主题
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("subscribe")]
public async Task<IActionResult> Subscribe([FromBody] SubscribeRequest request)
{
if (string.IsNullOrWhiteSpace(request.Topic))
{
return BadRequest("Topic is required");
}
var success = await _mqttClientHelper.SubscribeAsync(
request.Topic,
request.QualityOfServiceLevel ?? MqttQualityOfServiceLevel.AtMostOnce
);
return Ok(new { Success = success });
}
/// <summary>
/// 测试Mqtt,需先订阅主题,否则无法收到信息
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
[HttpPost("test")]
public async Task<IActionResult> Test([FromBody] TestRequest request)
{
if (!_mqttClientHelper.IsConnected)
{
// 连接Mqtt
bool connected = await _mqttClientHelper.ConnectFromConfigAsync();
if(!connected)
return BadRequest(new { Error = "MQTT client is not connected" });
}
// 发布测试消息
var message = $"{{\"message\":\"{request.Message}\",\"timestamp\":\"{DateTime.UtcNow:O}\"}}";
var publishSuccess = await _mqttClientHelper.PublishAsync(
request.Topic,
message,
request.QualityOfServiceLevel ?? MqttQualityOfServiceLevel.AtMostOnce
);
if (!publishSuccess)
{
return StatusCode(500, new { Error = "Failed to publish message" });
}
return Ok(new
{
Success = true,
Topic = request.Topic,
Message = message,
Timestamp = DateTime.UtcNow
});
}
/// <summary>
/// 接受消息事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnMessageReceived(object? sender, MqttApplicationMessageReceivedEventArgs e)
{
try
{
string payload = e.ApplicationMessage.ConvertPayloadToString() ?? string.Empty;
_logger.LogInformation("收到 MQTT 消息 - 主题: {Topic}, 内容: {Content}",
e.ApplicationMessage.Topic, payload);
}
catch (Exception ex)
{
_logger.LogError(ex, "处理 MQTT 消息时出错");
}
}
}
/// <summary>
/// MQTT 后台服务
/// </summary>
public class MqttBackgroundService : BackgroundService
{
private readonly IMqttClientHelper _mqttClientHelper;
private readonly ILogger<MqttBackgroundService> _logger;
private readonly MqttConfig? _config;
/// <summary>
/// 构造函数
/// </summary>
public MqttBackgroundService(
IMqttClientHelper mqttClientHelper,
ILogger<MqttBackgroundService> logger,
IOptions<MqttConfig>? config = null)
{
_mqttClientHelper = mqttClientHelper ?? throw new ArgumentNullException(nameof(mqttClientHelper));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_config = config?.Value;
// 订阅事件
_mqttClientHelper.MessageReceived += OnMessageReceived;
_mqttClientHelper.ConnectionStateChanged += OnConnectionStateChanged;
_mqttClientHelper.ReconnectStatusChanged += OnReconnectStatusChanged;
}
/// <summary>
/// 服务执行
/// </summary>
/// <param name="stoppingToken"></param>
/// <returns></returns>
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_logger.LogInformation("MQTT 后台服务启动");
// 连接到 MQTT 服务器
while (!stoppingToken.IsCancellationRequested)
{
try
{
if (_config != null && !string.IsNullOrEmpty(_config.Server))
{
_logger.LogInformation("正在连接到 MQTT 服务器: {Server}:{Port}",
_config.Server, _config.Port);
var connected = await _mqttClientHelper.ConnectFromConfigAsync(stoppingToken);
if (connected)
{
_logger.LogInformation("MQTT 连接成功");
// 订阅额外的主题(如果有)
await SubscribeAdditionalTopicsAsync(stoppingToken);
// 保持运行状态
while (!stoppingToken.IsCancellationRequested && _mqttClientHelper.IsConnected)
{
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
if (!_mqttClientHelper.IsConnected)
{
_logger.LogWarning("MQTT 连接断开,等待重连...");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
else
{
_logger.LogWarning("MQTT 连接失败,5 秒后重试...");
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
else
{
_logger.LogWarning("MQTT 配置无效,30 秒后重试...");
await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
}
}
catch (OperationCanceledException)
{
break;
}
catch (Exception ex)
{
_logger.LogError(ex, "MQTT 后台服务发生错误");
await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
}
}
_logger.LogInformation("MQTT 后台服务停止");
}
/// <summary>
/// 停止服务
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public override async Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("正在停止 MQTT 后台服务...");
// 断开 MQTT 连接
await _mqttClientHelper.DisconnectAsync(cancellationToken);
await base.StopAsync(cancellationToken);
}
/// <summary>
/// 订阅额外的主题
/// </summary>
private async Task SubscribeAdditionalTopicsAsync(CancellationToken cancellationToken)
{
// TODO:这里可以添加额外的主题订阅逻辑
// 例如:从数据库或其他配置源获取主题
var additionalTopics = new List<string>();
if (additionalTopics.Count != 0)
{
_logger.LogInformation("开始订阅额外的主题...");
await _mqttClientHelper.SubscribeMultipleAsync(additionalTopics, cancellationToken: cancellationToken);
}
}
/// <summary>
/// 消息接收事件处理
/// </summary>
private void OnMessageReceived(object? sender, MqttApplicationMessageReceivedEventArgs e)
{
try
{
string payload = e.ApplicationMessage.ConvertPayloadToString() ?? string.Empty;
_logger.LogDebug("收到消息 - 主题: {Topic}, 内容: {Content}",
e.ApplicationMessage.Topic, payload);
// TODO:处理订阅收到的消息
}
catch (Exception ex)
{
_logger.LogError(ex, "处理消息时出错");
}
}
/// <summary>
/// 连接状态变化事件处理
/// </summary>
private void OnConnectionStateChanged(object? sender, bool isConnected)
{
if (isConnected)
{
_logger.LogInformation("MQTT 连接已建立");
}
else
{
_logger.LogWarning("MQTT 连接已断开");
}
}
/// <summary>
/// 重连状态变化事件处理
/// </summary>
/// <param name="reconnectStatus"></param>
/// <param name="sender"></param>
public void OnReconnectStatusChanged(object? sender, ReconnectStatus reconnectStatus)
{
_logger.LogInformation($"MQTT 连接状态:{reconnectStatus.ToString()}");
}
}
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net10.0
- Microsoft.Extensions.Configuration (>= 10.0.0)
- Microsoft.Extensions.DependencyInjection (>= 10.0.0)
- Microsoft.Extensions.Hosting (>= 10.0.0)
- Microsoft.Extensions.Logging (>= 10.0.0)
- Microsoft.Extensions.Options (>= 10.0.0)
- MQTTnet (>= 5.0.1.1416)
-
net8.0
- Microsoft.Extensions.Configuration (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection (>= 8.0.0)
- Microsoft.Extensions.Hosting (>= 8.0.0)
- Microsoft.Extensions.Logging (>= 8.0.0)
- Microsoft.Extensions.Options (>= 8.0.0)
- MQTTnet (>= 5.0.1.1416)
-
net9.0
- Microsoft.Extensions.Configuration (>= 9.0.0)
- Microsoft.Extensions.DependencyInjection (>= 9.0.0)
- Microsoft.Extensions.Hosting (>= 9.0.0)
- Microsoft.Extensions.Logging (>= 9.0.0)
- Microsoft.Extensions.Options (>= 9.0.0)
- MQTTnet (>= 5.0.1.1416)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.