MQTTManager.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using UnityEngine;
  5. using Rocworks.Mqtt;
  6. namespace ToneTuneToolkit.MQTT
  7. {
  8. public class MQTTManager : MonoBehaviour
  9. {
  10. public static MQTTManager Instance;
  11. #region Path
  12. private string configPath = $"{Application.streamingAssetsPath}/configs/mqttconfig.json";
  13. #endregion
  14. public MqttClient MqttClient;
  15. // ==================================================
  16. private void Awake()
  17. {
  18. Instance = this;
  19. }
  20. private void Start()
  21. {
  22. Init();
  23. }
  24. // private void OnApplicationQuit()
  25. // {
  26. // Uninit();
  27. // }
  28. // ==================================================
  29. private void Init()
  30. {
  31. // MqttClient.Host = JsonManager.GetJson(configPath, "host");
  32. // MqttClient.Port = JsonManager.GetJson(configPath, "port");
  33. return;
  34. }
  35. // private void Uninit()
  36. // {
  37. // return;
  38. // }
  39. // ==================================================
  40. public void SetMQTTClientHost(string value)
  41. {
  42. MqttClient.Host = value;
  43. return;
  44. }
  45. public void SetMQTTClientPort(int value)
  46. {
  47. MqttClient.Port = value;
  48. return;
  49. }
  50. // ==================================================
  51. /// <summary>
  52. /// 发送消息
  53. /// </summary>
  54. /// <param name="topic"></param>
  55. /// <param name="message"></param>
  56. public void SendMessageOut(string topic, string message)
  57. {
  58. MqttClient.Connection.Publish(topic, message);
  59. Debug.Log($"[MQTT Manager] Message [<color=white>{message}</color>] send to [<color=white>{MqttClient.Host}:{MqttClient.Port}</color>].");
  60. return;
  61. }
  62. /// <summary>
  63. /// 接收消息
  64. /// </summary>
  65. /// <param name="value"></param>
  66. public void OnMessageArrived(MqttMessage value)
  67. {
  68. Debug.Log($"[MQTT Manager] Message [<color=white>{value}</color>] received.");
  69. return;
  70. }
  71. }
  72. }