终端一体化运控平台
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 

77 righe
2.5 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 userName, string Password, 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.UserName = userName;
  31. p.Password = Password;
  32. p.mqttClientConnectedHandlerDelegate = new MQTTnet.Client.Connecting.MqttClientConnectedHandlerDelegate(e =>
  33. {
  34. IsConnected = true;
  35. Connected?.Invoke();
  36. });
  37. //p.mqttClientDisconnectedHandlerDelegate = new MQTTnet.Client.Disconnecting.MqttClientDisconnectedHandlerDelegate(e =>
  38. //{
  39. // IsConnected = false;
  40. // LostConnect?.Invoke();
  41. //});
  42. p.ConnectedResult += (s, e) =>
  43. {
  44. client = e;
  45. };
  46. p.MqttApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
  47. {
  48. MessageRecive?.Invoke(Encoding.Default.GetString(e.ApplicationMessage.Payload));
  49. });
  50. });
  51. }
  52. public void CloseConnect()
  53. {
  54. client.Dispose();
  55. }
  56. public async void Publish(string topic, string content)
  57. {
  58. if (client.IsConnected)
  59. await client.PublishAsync(topic, content);
  60. }
  61. public async void Subscrib(params string[] topics)
  62. {
  63. foreach (var topic in topics)
  64. {
  65. await client.SubscribeAsync(new MqttTopicFilter() { Topic = topic, QualityOfServiceLevel = MQTTnet.Protocol.MqttQualityOfServiceLevel.AtMostOnce });
  66. }
  67. }
  68. }
  69. }