You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

133 lines
4.0KB

  1. import { Injectable } from '@angular/core';
  2. import {
  3. IMqttMessage,
  4. IMqttServiceOptions,
  5. MqttService,
  6. IPublishOptions,
  7. } from 'ngx-mqtt';
  8. import { IClientSubscribeOptions } from 'mqtt-browser';
  9. import {BehaviorSubject, Observable, Subject, Subscription} from 'rxjs';
  10. import {TOPIC_GETTING, TOPIC_INFO, TOPIC_LOG, TOPIC_SETTING} from "../../app.constants";
  11. @Injectable({
  12. providedIn: 'root'
  13. })
  14. export class MqttClientService {
  15. client: MqttService | undefined;
  16. constructor(private _mqttService: MqttService) {
  17. this.client = this._mqttService;
  18. }
  19. private curSubscription: Subscription | undefined;
  20. private settingSubscription: Subscription | undefined;
  21. connection = {
  22. hostname: 'broker.hivemq.com',
  23. clean: true,
  24. path:'/mqtt',
  25. port: 8884,
  26. reconnectPeriod: 4000,
  27. protocol: 'wss',
  28. }
  29. receiveNews = '';
  30. isConnection = false;
  31. private statusSubject = new BehaviorSubject<boolean>(this.isConnection);
  32. public status$ = this.statusSubject.asObservable();
  33. private messagesSubject$ = new BehaviorSubject(null);
  34. public messages$ = this.messagesSubject$.asObservable();
  35. private settingSubject$ = new BehaviorSubject(null);
  36. public setting$ = this.settingSubject$.asObservable();
  37. // 创建连接
  38. createConnection() {
  39. try {
  40. this.client?.connect(this.connection as IMqttServiceOptions)
  41. } catch (error) {
  42. console.log('mqtt.connect error', error);
  43. }
  44. this.client?.onConnect.subscribe(() => {
  45. this.isConnection = true;
  46. this.statusSubject.next(this.isConnection);
  47. console.log('Connection succeeded!');
  48. });
  49. this.client?.onError.subscribe((error: any) => {
  50. this.isConnection = false;
  51. this.statusSubject.next(this.isConnection);
  52. this.clearLog();
  53. console.log('Connection failed', error);
  54. });
  55. this.client?.onClose.subscribe((error: any) => {
  56. this.isConnection = false;
  57. this.statusSubject.next(this.isConnection);
  58. this.clearLog();
  59. console.log('Connection close', error);
  60. });
  61. }
  62. // 订阅主题
  63. getLog() {
  64. const { topic, qos } = {
  65. topic: TOPIC_LOG,
  66. qos: 0,
  67. };
  68. this.curSubscription = this.client?.observe(topic, { qos, dup: false } as IClientSubscribeOptions).subscribe((message: IMqttMessage) => {
  69. try {
  70. let plainMessage = "";
  71. for (var i = 0; i < message.payload.length; i++) {
  72. plainMessage += String.fromCharCode(parseInt(String(message.payload[i])));
  73. }
  74. console.log(JSON.parse(plainMessage));
  75. this.messagesSubject$.next(JSON.parse(plainMessage));
  76. }catch (e) {
  77. console.log(e);
  78. }
  79. });
  80. }
  81. // 订阅主题
  82. getSetting() {
  83. const { topic, qos } = {
  84. topic: TOPIC_SETTING,
  85. qos: 0,
  86. };
  87. this.settingSubscription = this.client?.observe(topic, { qos, dup: false } as IClientSubscribeOptions).subscribe((message: IMqttMessage) => {
  88. try {
  89. let plainMessage = "";
  90. for (var i = 0; i < message.payload.length; i++) {
  91. plainMessage += String.fromCharCode(parseInt(String(message.payload[i])));
  92. }
  93. console.log(JSON.parse(plainMessage));
  94. this.settingSubject$.next(JSON.parse(plainMessage));
  95. }catch (e) {
  96. console.log(e);
  97. }
  98. });
  99. }
  100. // 取消订阅
  101. clearLog() {
  102. this.curSubscription?.unsubscribe()
  103. this.settingSubscription?.unsubscribe();
  104. }
  105. // 发送消息
  106. doPublish(data: any) {
  107. this.client?.unsafePublish(TOPIC_INFO, JSON.stringify(data), {qos: 0} as IPublishOptions);
  108. }
  109. // 发送消息
  110. sendPublish(data: any, topic = TOPIC_INFO) {
  111. this.client?.unsafePublish(topic, JSON.stringify(data), {qos: 0} as IPublishOptions);
  112. // this.client?.publish("isoft/node 4/in4", JSON.stringify(data), {qos: 0} as IPublishOptions).subscribe();
  113. }
  114. // 断开连接
  115. destroyConnection() {
  116. try {
  117. this.client?.disconnect(true)
  118. this.isConnection = false
  119. console.log('Successfully disconnected!')
  120. } catch (error: any) {
  121. console.log('Disconnect failed', error.toString())
  122. }
  123. }
  124. }