Unable to connect to MQTT broker via ngx-mqtt in angular8

╄→гoц情女王★ 提交于 2020-05-15 18:52:45

问题


No matter what i do i can't connect to a mqtt broker via websocket in my angular application (trying in chrome and firefox). For simplicity i'm using HiveMQ broker, i've published on the topic /gat/38/openReservationRequests some data

I've followed this medium article on how to connect to mqtt in angular using ngx-mqtt but for me it is not working.

In my app:

I've installed the module

npm install ngx-mqtt --save

i've added the configuration and set the module forRoot in my app.module.ts

...
export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {
  connectOnCreate: true,
  hostname: 'broker.hivemq.com',
  port: 8000,
  path: '/gat/38/openReservationRequests',
  protocol: 'ws',
};

...
imports: [
    ...
    MqttModule.forRoot(MQTT_SERVICE_OPTIONS),
    ...
  ],
...

i'm executing this function inside the ngOnInit of app.component.ts

...
import { IMqttMessage, MqttConnectionState, MqttService } from 'ngx-mqtt';
...

constructor(private mqttService: MqttService) {
    this.mqttService.state.subscribe((s: MqttConnectionState) => {
      const status = s === MqttConnectionState.CONNECTED ? 'CONNECTED' : 'DISCONNECTED';
      this.status.push(`Mqtt client connection status: ${status}`);
    });
  }

ngOnInit() {

    this.subscription = this.mqttService
                            .observe('/gat/38/openReservationRequests')
                            .subscribe((message: IMqttMessage) => {
                              this.msg = message;
                              console.log('msg: ', message);
                              console.log('Message: ' + message.payload.toString() + 'for topic: ' + message.topic);
                              console.log('subscribed to topic: ' + /gat/38/openReservationRequests);
                            });

}

but i am always getting this error:

core.js:6014 ERROR TypeError: Cannot read property 'resubscribe' of undefined
    at MqttClient.subscribe (mqtt.min.js:1)
    at mqtt.service.js:211
    at Observable._subscribe (using.js:8)
    at Observable._trySubscribe (Observable.js:42)
    at Observable.subscribe (Observable.js:28)
    at FilterOperator.call (filter.js:13)
    at Observable.subscribe (Observable.js:23)
    at Observable.connect (ConnectableObservable.js:30)
    at RefCountOperator.call (refCount.js:17)
    at Observable.subscribe (Observable.js:23)

mqtt.min.js:1 WebSocket connection to 'ws://broker.hivemq.com:8000/gat/38/openReservationRequests' failed: Connection closed before receiving a handshake response

if i specify the clientId inside the MQTT_SERVICE_OPTIONS i still get the same error.

if i change the protocol to wss i get a different error:

core.js:6014 ERROR TypeError: Cannot read property 'resubscribe' of undefined
    at MqttClient.subscribe (mqtt.min.js:1)
    at mqtt.service.js:211
    at Observable._subscribe (using.js:8)
    at Observable._trySubscribe (Observable.js:42)
    at Observable.subscribe (Observable.js:28)
    at FilterOperator.call (filter.js:13)
    at Observable.subscribe (Observable.js:23)
    at Observable.connect (ConnectableObservable.js:30)
    at RefCountOperator.call (refCount.js:17)
    at Observable.subscribe (Observable.js:23)

mqtt.min.js:1 WebSocket connection to 'wss://broker.hivemq.com:8000/gat/38/openReservationRequests' failed: Error in connection establishment: net::ERR_CONNECTION_CLOSED

If i try to connect manually inside my app.component.ts ngOnInit before observing the topic:

this.mqttService.connect({
  hostname: 'broker.hivemq.com',
  port: 8000,
  path: '/gat/38/openReservationRequests',
  clientId: '34er23qwrfq42w3' //those are just random digits
});

i still get the error above. For me it would be ideal to connect in some inner component (accessible after the user is authenticated) because i will have my private mqtt broker and the topic will depend on the logged user information.

I've tried any combination of protocol with/without cliendId etc but at this point i don't know what is wrong. I've already fully recompiled my app lots of times, i've tried publishing it on my test-server which has a ssl certificate but nothing changed.

Resolved thanks to @Anant Lalchandani i set the correct path.

The other problem was that '/mytopic' and 'mytopic' are indeed two different topic and i was using it wrong too. This is my code, updated: app.module.ts

export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {
  connectOnCreate: false,
  hostname: 'broker.hivemq.com',
  port: 8000,
  path: '/mqtt'
};

appcomponent.ts (inside ngOnInit for now)

 this.mqttService.connect({
      hostname: 'broker.hivemq.com',
      port: 8000,
      path: '/mqtt',
      clientId: '1234e3qer23rf'
    });

 this.mqttService.onConnect
        .subscribe(
          connack=> {
            console.log('CONNECTED');
            console.log(connack);
          }
        );

this.mqttService.observe('gat/38/openReservationRequests')
        .subscribe((message: IMqttMessage) => {
          this.msg = message;
          console.log(new TextDecoder('utf-8').decode(message.payload));
        });

回答1:


I have checked the code snippets you shared in question.

In your app.module.ts, the path value should be '/mqtt'. You have set the topic as the value of path here. The topic can only be subscribed/published. As you are using a topic as a path value at the time of connecting to a websocket, your application will not be able to connect to websocket at the first place.

The reason why we need to use /mqtt as a path is it specifies you are sending MQTT messages over the WebSocket protocol.

The documentation of HiveMQ itself stated to use the path as '/mqtt' in its example. You can check the documentation here.



来源:https://stackoverflow.com/questions/59265772/unable-to-connect-to-mqtt-broker-via-ngx-mqtt-in-angular8

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!