MQTT 与 Ionic 3 的连接

Cod*_*ine 3 javascript mqtt typescript ionic3 angular

我需要在我的 Ionic 3 应用程序中使用发布订阅方法。

我关注了这个页面

有什么方法可以将 MQTT 与我们的 Ionic 3 应用程序联系起来?如果是,怎么会?我究竟需要怎么做才能成功连接?

ng2-mqtt使用安装服务

npm install ng2-mqtt --save
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

index.html

<script src="cordova.js"></script>
<script src="node_modules/ng2-mqtt/mqttws31.js" type="text/javascript"></script>
Run Code Online (Sandbox Code Playgroud)

home.ts

import {Paho} from 'mqttws31'

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

      private _client: Paho.MQTT.Client;

      constructor(public paho: Paho) {

      }
         this._client = new Paho.MQTT.Client("52.66.30.178", 1883, "path", "someclient_id");

        this._client.onConnectionLost = (responseObject: Object) => {
          console.log('Connection lost.');
        this.getServerMessage();

         this._client.onMessageArrived = (message: Paho.MQTT.Message) => {
      console.log('Message arrived.');
    };

    this._client.connect({ onSuccess: this.onConnected.bind(this); });
  }
Run Code Online (Sandbox Code Playgroud)

我仍然无法让它工作。

任何建议和更改都会对我有所帮助。我被卡住了请做。

Cod*_*ine 5

在搜索并尝试了一段时间后,我找到了这个解决方案,如果你想在你的项目中使用 MQTT,你可以使用这个库。

使用npm install ngx-mqtt --save安装它

用法:app.module.ts

import { Observable } from 'rxjs/Observable';
import {
  IMqttMessage,
  MqttModule,
  MqttService
} from 'ngx-mqtt';

export const MQTT_SERVICE_OPTIONS = {
  hostname: '13.127.53.13',
  port: 9001,
  path: '/mqtt'
};

export function mqttServiceFactory() {
  return new MqttService(MQTT_SERVICE_OPTIONS);
}

@NgModule({
  imports: [
    BrowserModule,
    HttpModule,
    MqttModule.forRoot({
      provide: MqttService,
      useFactory: mqttServiceFactory
    }),
    IonicModule.forRoot(MyApp)
  ]
Run Code Online (Sandbox Code Playgroud)

然后您可以在您的页面中使用它,例如:(例如:home.ts 文件)

import { IMqttMessage, MqttModule, MqttService } from 'ngx-mqtt';
import { Observable } from 'rxjs/Observable';

export class HomePage  {

constructor( private _mqttService: MqttService)
{
   this._mqttService.observe('home/door').subscribe((message: MqttMessage) => 
   {
   this.sensor1 = message.payload.toString();
   console.log(this.sensor1);
   });
}

 publishMessage()
 {
  this._mqttService.unsafePublish("home/button", "on", {qos: 0, retain: false});
 }
Run Code Online (Sandbox Code Playgroud)

有关此库的更多信息: https : //github.com/sclausen/ngx-mqtt