Bläddra i källkod

添加项目文件。

CrazyIter 5 år sedan
förälder
incheckning
73555bcf25

+ 20 - 0
MQTT-Broker/Controllers/TestAPIController.cs

@@ -0,0 +1,20 @@
+using Microsoft.AspNetCore.Mvc;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace MQTT_Broker.Controllers
+{ //[Authorize]
+    [Route("api/[controller]")]
+    [ApiController]
+    public class TestAPIController
+    {
+        [HttpGet("aa")]
+        public IActionResult Get()
+        {
+            return new JsonResult(new { a = "aa", c = "bb" });
+        }
+    }
+
+}

+ 13 - 0
MQTT-Broker/MQTT-Broker.csproj

@@ -0,0 +1,13 @@
+<Project Sdk="Microsoft.NET.Sdk.Web">
+
+  <PropertyGroup>
+    <TargetFramework>netcoreapp3.1</TargetFramework>
+    <RootNamespace>MQTT_Broker</RootNamespace>
+  </PropertyGroup>
+
+  <ItemGroup>
+    <PackageReference Include="Microsoft.AspNetCore.Server.Kestrel.Https" Version="2.2.0" />
+    <PackageReference Include="MQTTnet.AspNetCore" Version="3.0.11" />
+    <PackageReference Include="MQTTnet.Extensions.WebSocket4Net" Version="3.0.11" />
+  </ItemGroup>
+</Project>

+ 42 - 0
MQTT-Broker/Program.cs

@@ -0,0 +1,42 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Security.Cryptography.X509Certificates;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.Server.Kestrel.Core;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using MQTTnet.AspNetCore;
+
+namespace MQTT_Broker
+{
+    public class Program
+    {
+        public static void Main(string[] args)
+        {
+            CreateHostBuilder(args).Build().Run();
+        }
+
+        public static IHostBuilder CreateHostBuilder(string[] args) =>
+            Host.CreateDefaultBuilder(args)
+                .ConfigureWebHostDefaults(webBuilder =>
+                {
+                    webBuilder.UseKestrel(o=> {
+                        o.ListenAnyIP(1883, l => l.UseMqtt());
+                        o.ListenAnyIP(9001, l => l.UseMqtt());
+                        o.ListenAnyIP(9002, l => l.UseMqtt());
+                        o.ListenAnyIP(5000); // default http pipeline
+
+                        o.ListenAnyIP(5001, listenOptions =>
+                        {
+                            //   listenOptions.UseHttps("habook.pfx", "habook");
+                            listenOptions.UseHttps("cert.pfx", "Pa$$w0rd");
+                        });
+                    }).UseStartup<Startup>();
+                });
+    }
+}

+ 30 - 0
MQTT-Broker/Properties/launchSettings.json

@@ -0,0 +1,30 @@
+{
+  "$schema": "http://json.schemastore.org/launchsettings.json",
+  "iisSettings": {
+    "windowsAuthentication": false,
+    "anonymousAuthentication": true,
+    "iisExpress": {
+      "applicationUrl": "http://localhost:61500",
+      "sslPort": 44388
+    }
+  },
+  "profiles": {
+    "IIS Express": {
+      "commandName": "IISExpress",
+      "launchBrowser": true,
+      "launchUrl": "aa",
+      "environmentVariables": {
+        "ASPNETCORE_ENVIRONMENT": "Development"
+      }
+    },
+    "MQTT_Broker": {
+      "commandName": "Project",
+      "launchBrowser": true,
+      "launchUrl": "api/TestAPI/aa",
+      "applicationUrl": "https://localhost:5001;http://localhost:5000",
+      "environmentVariables": {
+        "ASPNETCORE_ENVIRONMENT": "Development"
+      }
+    }
+  }
+}

+ 196 - 0
MQTT-Broker/Startup.cs

@@ -0,0 +1,196 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Security.Authentication;
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.AspNetCore.Builder;
+using Microsoft.AspNetCore.Hosting;
+using Microsoft.AspNetCore.HttpsPolicy;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.WebSockets;
+using Microsoft.Extensions.Configuration;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using MQTTnet;
+using MQTTnet.AspNetCore;
+using MQTTnet.Client.Receiving;
+using MQTTnet.Protocol;
+using MQTTnet.Server;
+namespace MQTT_Broker
+{
+    public class Startup
+    {
+        //private IServiceProvider _serviceProvider;
+
+     
+        public Startup(IConfiguration configuration)
+        {
+            Configuration = configuration;
+          // _logger = logger;
+        }
+
+        public IConfiguration Configuration { get; }
+
+        // This method gets called by the runtime. Use this method to add services to the container.
+        public void ConfigureServices(IServiceCollection services)
+        {
+            services.AddControllers();
+            services.AddHostedMqttServerWithServices(
+            builder =>
+                {
+                    //builder.WithDefaultEndpoint();
+
+                    builder.WithDefaultEndpointPort(1883);
+                    builder.WithConnectionValidator(c =>
+                        {
+                    //从IServiceCollection中构建     ServiceProvider, 用以使用注入访问数据库的服务
+                    //  var serprovider = services.BuildServiceProvider();
+
+                  //  _logger.LogInformation($" ClientId:{c.ClientId} Endpoint:{c.Endpoint} Username:{c.Username} Password:{c.Password} WillMessage:{c.WillMessage}");
+
+                            //if (c.ClientId.Length < 5)
+                            //{
+                            //    c.ReasonCode = MqttConnectReasonCode.ClientIdentifierNotValid;
+                            //    return;
+                            //}
+
+                            //if (c.Username != "admin")
+                            //{
+                            //    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
+                            //    return;
+                            //}
+
+                            //if (c.Password != "public")
+                            //{
+                            //    c.ReasonCode = MqttConnectReasonCode.BadUserNameOrPassword;
+                            //    return;
+                            //}
+                            c.ReasonCode = MqttConnectReasonCode.Success;
+                        })
+                    .WithApplicationMessageInterceptor(context =>
+                        {
+                            //if (MqttTopicFilterComparer.IsMatch(context.ApplicationMessage.Topic, "/myTopic/WithTimestamp/#"))
+                            //{
+                            //    context.ApplicationMessage.Payload = Encoding.UTF8.GetBytes(DateTime.Now.ToString("O"));
+                            //}
+
+                            //if (context.ApplicationMessage.Topic == "not_allowed_topic")
+                            //{
+                            //    context.AcceptPublish = false;
+                            //    context.CloseConnection = true;
+                            //}
+
+                           // _logger.Log(LogLevel.Information, $"clientId:{context.ClientId}, topic:{context.ApplicationMessage.Topic}");
+                          //  _logger.Log(LogLevel.Information, $"Payload:{Encoding.Default.GetString(context.ApplicationMessage.Payload)}");
+                        })///订阅拦截验证
+                .WithSubscriptionInterceptor((context) =>
+                {
+                    //if (context.TopicFilter.Topic.StartsWith("admin/foo/bar") && context.ClientId != "theAdmin")
+                    //{
+                    //    context.AcceptSubscription = false;
+                    //}
+
+                    //if (context.TopicFilter.Topic.StartsWith("the/secret/stuff") && context.ClientId != "Imperator")
+                    //{
+                    //    context.AcceptSubscription = false;
+                    //    context.CloseConnection = true;
+                    //}
+
+                    //context.TopicFilter.Topic.start
+                });
+                });
+            services.AddMqttTcpServerAdapter();
+            services.AddMqttWebSocketServerAdapter();
+            services.AddMqttConnectionHandler() .AddConnections();
+            //.AddMqttConnectionHandler().AddConnections().AddMqttTcpServerAdapter();
+            //var mqttServerOptions = new MqttServerOptionsBuilder().WithEncryptionSslProtocol(SslProtocols.None)
+            //  .WithDefaultEndpointPort(9001).WithEncryptedEndpointPort(9002)
+            // .WithoutDefaultEndpoint()
+            // .Build();
+            //services
+            //    .AddHostedMqttServer(mqttServerOptions)
+            //    .AddMqttWebSocketServerAdapter()
+            //    .AddMqttConnectionHandler()
+            //    //.AddWebSockets(x => { x = new WebSocketOptions { KeepAliveInterval = new TimeSpan(100000000) }; })
+            //    .AddConnections();
+        }
+
+        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
+        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+        {
+            if (env.IsDevelopment())
+            {
+                app.UseDeveloperExceptionPage();
+            }
+            
+            app.UseRouting();
+            app.UseAuthorization();
+            //app.UseMqttEndpoint("/mqtt");
+            app.UseEndpoints(endpoints =>
+            {
+                endpoints.MapMqtt("/mqtt");
+                endpoints.MapControllers();
+            });
+           // app.UseConnections(c => c.MapMqtt("/mqtt"));
+            app.UseMqttServer(
+                server =>
+                {
+                    server.UseApplicationMessageReceivedHandler(e =>
+                    {
+
+                    });
+                     
+                    server.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
+                    {
+                        Console.WriteLine(
+                            $"'{e.ClientId}' reported '{e.ApplicationMessage.Topic}' > '{Encoding.UTF8.GetString(e.ApplicationMessage.Payload ?? new byte[0])}'",
+                            ConsoleColor.Magenta);
+                    });
+                    server.StartedHandler = new MqttServerStartedHandlerDelegate((
+                        e =>
+                        {
+
+                        }));
+                    server.StoppedHandler = new MqttServerStoppedHandlerDelegate(
+                        e =>
+                        {
+
+                        });
+
+                    server.ClientConnectedHandler = new MqttServerClientConnectedHandlerDelegate(
+                        e =>
+                        {
+                          //  _logger.LogInformation($"{e.ClientId} is connectioned");
+                           // _logger.LogInformation($"目前连接总数:{ server.GetClientStatusAsync().Result.Count}");
+                        });
+                    server.ClientDisconnectedHandler = new MqttServerClientDisconnectedHandlerDelegate(
+                        e =>
+                        {
+
+                           // _logger.LogInformation($"{e.ClientId} is disconnectioned");
+                          //  _logger.LogInformation($"目前连接总数:{ server.GetClientStatusAsync().Result.Count}");
+                        });
+                    //开启订阅以及取消订阅
+                    server.ClientSubscribedTopicHandler = new MqttServerClientSubscribedHandlerDelegate((args) => {
+                        Console.WriteLine("订阅" + args.ClientId + args.TopicFilter.Topic);
+                    });
+                    server.ClientUnsubscribedTopicHandler = new MqttServerClientUnsubscribedTopicHandlerDelegate((args) => {
+                        Console.WriteLine("取消订阅" + args.ClientId + args.TopicFilter);
+                    });
+                    server.UseClientConnectedHandler(x => {
+                        Console.WriteLine(x.ClientId + "连接");
+                    });
+                    server.UseClientDisconnectedHandler(x => {
+                        Console.WriteLine(x.ClientId + "断开连接");
+                    });
+                });
+            //app.UseMqttEndpoint("/mqtt");
+            
+            app.UseHttpsRedirection();
+           
+          
+        }
+    }
+}

+ 9 - 0
MQTT-Broker/appsettings.Development.json

@@ -0,0 +1,9 @@
+{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft": "Warning",
+      "Microsoft.Hosting.Lifetime": "Information"
+    }
+  }
+}

+ 10 - 0
MQTT-Broker/appsettings.json

@@ -0,0 +1,10 @@
+{
+  "Logging": {
+    "LogLevel": {
+      "Default": "Information",
+      "Microsoft": "Warning",
+      "Microsoft.Hosting.Lifetime": "Information"
+    }
+  },
+  "AllowedHosts": "*"
+}

+ 25 - 0
TMD-MQTT.sln

@@ -0,0 +1,25 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30104.148
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MQTT-Broker", "MQTT-Broker\MQTT-Broker.csproj", "{F9BD7C23-AEC0-4058-A448-EA40FE1673A5}"
+EndProject
+Global
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
+		Debug|Any CPU = Debug|Any CPU
+		Release|Any CPU = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
+		{F9BD7C23-AEC0-4058-A448-EA40FE1673A5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{F9BD7C23-AEC0-4058-A448-EA40FE1673A5}.Debug|Any CPU.Build.0 = Debug|Any CPU
+		{F9BD7C23-AEC0-4058-A448-EA40FE1673A5}.Release|Any CPU.ActiveCfg = Release|Any CPU
+		{F9BD7C23-AEC0-4058-A448-EA40FE1673A5}.Release|Any CPU.Build.0 = Release|Any CPU
+	EndGlobalSection
+	GlobalSection(SolutionProperties) = preSolution
+		HideSolutionNode = FALSE
+	EndGlobalSection
+	GlobalSection(ExtensibilityGlobals) = postSolution
+		SolutionGuid = {47FBBEAE-4855-49E2-A341-356C9FA74AAA}
+	EndGlobalSection
+EndGlobal