MqttClientService.cs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using Edge.Core.Core.database;
  2. using MQTTnet;
  3. using MQTTnet.Client;
  4. using Newtonsoft.Json;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. namespace Edge.Core.MqttClient
  11. {
  12. public class MqttClientService: IMqttClientService
  13. {
  14. private static NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
  15. private string[] topics;//需要订阅的主题
  16. private IMqttClient _mqttClient; //mqtt 客户端
  17. public MqttClientService() { }
  18. public event EventHandler<MqttClientConnectedEventArgs> OnConnect;
  19. public event EventHandler<MqttClientDisconnectedEventArgs> OnDisconnect;
  20. public event EventHandler<MqttApplicationMessageReceivedEventArgs> OnApplicationMessageReceived;
  21. public void Public(string topic, string paramsJson)
  22. {
  23. }
  24. public void Start()
  25. {
  26. using (var dbContext = new MysqlDbContext())
  27. {
  28. Domain.FccStationInfo.FccStationInfo? fccStationInfo = dbContext.FccStationInfos.FirstOrDefault();
  29. string? mqttService = fccStationInfo?.MqttService;
  30. string? buildId = fccStationInfo?.BuildId;
  31. if (mqttService == null || buildId == null)
  32. {
  33. Logger.Info($"can not get mqttService:{mqttService} and buildId:{buildId}");
  34. return;
  35. }
  36. string[] hostAndPort = mqttService.Split(":");
  37. MqttClientOptions mqttClientOptions = new MqttClientOptionsBuilder()
  38. .WithTcpServer(hostAndPort[0], hostAndPort[1].ToString().ToInt())
  39. .WithClientId(buildId)
  40. .WithCleanSession()
  41. .WithTlsOptions(new MqttClientTlsOptions()
  42. {
  43. UseTls = false
  44. })
  45. .Build();
  46. _mqttClient = new MqttFactory().CreateMqttClient();
  47. this.topics = new string[] { $"fromClound/{buildId}" };
  48. _mqttClient.ConnectedAsync += mqttConnected;
  49. _mqttClient.DisconnectedAsync += mqttDisConnected;
  50. _mqttClient.ApplicationMessageReceivedAsync += mqttOnReceive;
  51. _mqttClient.ConnectAsync(mqttClientOptions);
  52. }
  53. }
  54. /// <summary>
  55. /// MQTT 已连接事件
  56. /// </summary>
  57. /// <param name="args"></param>
  58. /// <returns></returns>
  59. private Task mqttConnected(MqttClientConnectedEventArgs args)
  60. {
  61. Logger.Info($"mqtt connected");
  62. topics.ForEach(topic =>
  63. {
  64. _mqttClient.SubscribeAsync(topic, MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce);
  65. });
  66. OnConnect?.Invoke(this, args);
  67. return Task.CompletedTask;
  68. }
  69. /// <summary>
  70. /// MQTT 断开连接
  71. /// </summary>
  72. /// <param name="args"></param>
  73. /// <returns></returns>
  74. private Task mqttDisConnected(MqttClientDisconnectedEventArgs args)
  75. {
  76. Logger.Info($"mqtt disconnect",JsonConvert.SerializeObject(args));
  77. Thread.Sleep(3000);
  78. Start();
  79. OnDisconnect?.Invoke(this, args);
  80. return Task.CompletedTask;
  81. }
  82. /// <summary>
  83. /// MQTT 获取到数据
  84. /// </summary>
  85. /// <param name="args"></param>
  86. /// <returns></returns>
  87. private Task mqttOnReceive(MqttApplicationMessageReceivedEventArgs args)
  88. {
  89. Logger.Info($"mqtt receive message");
  90. OnApplicationMessageReceived?.Invoke(this, args);
  91. return Task.CompletedTask;
  92. }
  93. }
  94. }