终端一体化运控平台
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 

75 рядки
2.4 KiB

  1. using BPA.MQTTClient;
  2. using Microsoft.Extensions.Configuration;
  3. using MQTTnet;
  4. using MQTTnet.Client;
  5. using MQTTnet.Client.Receiving;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. namespace BPASmartClient.MQTT
  13. {
  14. public class MQTTProxy
  15. {
  16. public Action<string> MessageRecive { get; set; }
  17. public Action Connected { get; set; }
  18. public Action LostConnect { get; set; }
  19. public bool IsConnected { get; set; }
  20. private IMqttClient client;
  21. public void Connect(string ip, int port, string clientId)
  22. {
  23. IConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
  24. configurationBuilder.AddMqttClientHostedService(p =>
  25. {
  26. p.Server = ip;
  27. p.Port = port;
  28. p.UserName = "rafiul";
  29. p.Password = "12345678";
  30. p.mqttClientConnectedHandlerDelegate = new MQTTnet.Client.Connecting.MqttClientConnectedHandlerDelegate(e =>
  31. {
  32. IsConnected = true;
  33. Connected?.Invoke();
  34. });
  35. //p.mqttClientDisconnectedHandlerDelegate = new MQTTnet.Client.Disconnecting.MqttClientDisconnectedHandlerDelegate(e =>
  36. //{
  37. // IsConnected = false;
  38. // LostConnect?.Invoke();
  39. //});
  40. p.ConnectedResult += (s, e) =>
  41. {
  42. client = e;
  43. };
  44. p.MqttApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
  45. {
  46. MessageRecive?.Invoke(Encoding.Default.GetString(e.ApplicationMessage.Payload));
  47. });
  48. });
  49. }
  50. public void CloseConnect()
  51. {
  52. client.Dispose();
  53. }
  54. public async void Publish(string topic, string content)
  55. {
  56. if (client.IsConnected)
  57. await client.PublishAsync(topic, content);
  58. }
  59. public async void Subscrib(params string[] topics)
  60. {
  61. foreach (var topic in topics)
  62. {
  63. await client.SubscribeAsync(new MqttTopicFilter() { Topic = topic, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
  64. }
  65. }
  66. }
  67. }