MqttNet.DependencyInjection 1.0.4

dotnet add package MqttNet.DependencyInjection --version 1.0.4
                    
NuGet\Install-Package MqttNet.DependencyInjection -Version 1.0.4
                    
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="MqttNet.DependencyInjection" Version="1.0.4" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MqttNet.DependencyInjection" Version="1.0.4" />
                    
Directory.Packages.props
<PackageReference Include="MqttNet.DependencyInjection" />
                    
Project file
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 MqttNet.DependencyInjection --version 1.0.4
                    
#r "nuget: MqttNet.DependencyInjection, 1.0.4"
                    
#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 MqttNet.DependencyInjection@1.0.4
                    
#: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=MqttNet.DependencyInjection&version=1.0.4
                    
Install as a Cake Addin
#tool nuget:?package=MqttNet.DependencyInjection&version=1.0.4
                    
Install as a Cake Tool

MqttNet.DependencyInjection

基于MqttNet进行的服务封装中间件

Mqtt服务配置

添加服务配置

首先在 Startup.cs文件进行配置:

public void ConfigureServices(IServiceCollection services)
{
    //......
    services.AddMqttClient(options => {
        options.Server = "127.0.0.1"; //Mqtt服务器ip
        options.Port = 60005;  //端口
        options.UserName = "";  //用户名
        options.Passowrd = ""; //密码
        options.ClientId = "ClientId";  //配置ClientId
    }).AddEventHandler<MqttClientEventHandler>()  //Topic配置和消息处理 handler类,
    //开启心跳
    .WithHeartBeat(options => 
    {
        options.EnableHeartBeat = true; //启用
        options.PubHeartBeatTopic = "Clould/HeartBeat"; //发送心跳的Topic
        options.HeartBeatinterval = TimeSpan.FromSeconds(1); //时间间隔
        options.DeviceNo = "deviceNo"; //设备Id
        options.CustmData = new{}; //自定义数据,心跳自动携带
    })
    //开启动态订阅和退订
    .WithDynamicScribe(options =>
    {
        options.EnableDynamicSubcribe = true; //启用
        options.SubcribeHeartBeatTopic = "Clould/HeartBeat"; //接收心跳的Topic
        options.DynamicSubcribeinterval = TimeSpan.FromSeconds(1); //时间间隔
    });
    
}

处理类编写

需要继承 AbsractClientHandler 抽象类

    public class MqttClientEventHandler : AbsractClientHandler
    {


        public MqttClientEventHandler(IMqttPublisher mqttPublisher) : base(mqttPublisher)
        {

        }
        //设置需要订阅的Topic列表,
        //未开启动态订阅,将遍历所有主题全部订阅
        //开启动态订阅,通过心跳解析,对其对应的ClientId下的Topic列表进行订阅和退订
        public override void SetTopic(out List<ClientTopic> mqttClient)
        {
            mqttClient = new List<ClientTopic>()
            {
                new ClientTopic(){ 
                    DeviceNo = "deviceNo", 
                    TopicList = new List<string>
                    {
                        "topic1",
                        "topic2"
                    }
                }
            };
        }

        //心跳处理方法
        public override void HeartBeatReceived(HeartBeatArgs args)
        {
        }

        //消息处理方法,
        public override void MessageReceived(MessageReceiveArgs args)
        {
            _mqttPublisher.PublishAsync(); //内置的发送信息服务
            Console.WriteLine("### 收到来自服务器端的消息 ###");
            // 收到的消息主题
            string topic = args.Topic;
            // 收到的的消息内容
            string payload = args.Message;
            // 收到的发送级别(Qos)
            var qos = args.QosLevel;
            // 收到的消息保持形式
            bool retain = args.Retain;
            args.AcknowledgeAsync(new CancellationTokenSource().Token);
            var message = $"主题: [{topic}] 内容: [{payload}] Qos: [{qos}] Retain:[{retain}]";
            Console.WriteLine(message);
        }


    }

发送消息

通过依赖注入获取发送信息接口服务

    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IMqttPublisher _mqttPublisher;

        public WeatherForecastController(ILogger<WeatherForecastController> logger,IMqttPublisher mqttPublisher)
        {
            _logger = logger;
            _mqttPublisher = mqttPublisher; //依赖注入赋值对象
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            _mqttPublisher.PublishAsync("topic","message"); //调用发送信息方法

            
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
     }
Product 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 was computed.  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 was computed.  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.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.4 132 8/1/2024
1.0.3 112 8/1/2024