Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

119 rindas
3.9 KiB

  1. using Microsoft.AspNetCore;
  2. using Microsoft.AspNetCore.Hosting;
  3. using Microsoft.Extensions.Configuration;
  4. using MQTTnet.AspNetCore;
  5. using MQTTnetServer.Settings;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Net;
  10. namespace MQTTnetServer
  11. {
  12. /// <summary>
  13. /// Main Entry point
  14. /// </summary>
  15. public class Program
  16. {
  17. /// <summary>
  18. /// Main
  19. /// </summary>
  20. /// <param name="args"></param>
  21. public static void Main(string[] args)
  22. {
  23. try
  24. {
  25. CreateWebHostBuilder(args).Build().Run();
  26. }
  27. catch (FileNotFoundException e)
  28. {
  29. Console.WriteLine("Could not find application settings file in: " + e.FileName);
  30. return;
  31. }
  32. }
  33. /// <summary>
  34. /// Configure and Start Kestrel
  35. /// </summary>
  36. /// <param name="args"></param>
  37. /// <returns></returns>
  38. public static IWebHostBuilder CreateWebHostBuilder(string[] args)
  39. {
  40. var webHost = WebHost.CreateDefaultBuilder(args);
  41. var listen = ReadListenSettings();
  42. webHost
  43. .UseKestrel(o =>
  44. {
  45. if (listen?.Length > 0)
  46. {
  47. foreach (var item in listen)
  48. {
  49. if (item.Address?.Trim() == "*")
  50. {
  51. if (item.Protocol == ListenProtocolTypes.MQTT)
  52. {
  53. o.ListenAnyIP(item.Port, c => c.UseMqtt());
  54. }
  55. else
  56. {
  57. o.ListenAnyIP(item.Port);
  58. }
  59. }
  60. else if (item.Address?.Trim() == "localhost")
  61. {
  62. if (item.Protocol == ListenProtocolTypes.MQTT)
  63. {
  64. o.ListenLocalhost(item.Port, c => c.UseMqtt());
  65. }
  66. else
  67. {
  68. o.ListenLocalhost(item.Port);
  69. }
  70. }
  71. else
  72. {
  73. if (IPAddress.TryParse(item.Address, out var ip))
  74. {
  75. if (item.Protocol == ListenProtocolTypes.MQTT)
  76. {
  77. o.Listen(ip, item.Port, c => c.UseMqtt());
  78. }
  79. else
  80. {
  81. o.Listen(ip, item.Port);
  82. }
  83. }
  84. }
  85. }
  86. }
  87. else
  88. {
  89. o.ListenAnyIP(1883, l => l.UseMqtt());
  90. o.ListenAnyIP(5000);
  91. }
  92. });
  93. webHost.UseStartup<Startup>();
  94. return webHost;
  95. }
  96. /// <summary>
  97. /// Read Application Settings
  98. /// </summary>
  99. /// <returns></returns>
  100. public static ListenModel[] ReadListenSettings()
  101. {
  102. var builder = new ConfigurationBuilder()
  103. .AddJsonFile("appsettings.json")
  104. .AddEnvironmentVariables()
  105. .Build();
  106. var listen = new List<ListenModel>();
  107. builder.Bind("MQTTnetServer:Listen", listen);
  108. return listen.ToArray();
  109. }
  110. }
  111. }