【问题标题】:MQTT Connection with Ionic 3MQTT 与 Ionic 3 的连接
【发布时间】:2018-07-20 00:48:44
【问题描述】:

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

我关注了this page

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

我安装了ng2-mqtt 服务使用

npm install ng2-mqtt --save

这是我的代码:

index.html

<script src="cordova.js"></script>
<script src="node_modules/ng2-mqtt/mqttws31.js" type="text/javascript"></script>

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); });
  }

我还是不能让它工作。

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

【问题讨论】:

    标签: javascript angular typescript ionic3 mqtt


    【解决方案1】:

    经过一段时间的搜索和尝试,我找到了这个解决方案,如果你想在项目中使用 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)
      ]
    

    然后您可以在您的页面中使用它,例如:(例如: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});
     }
    

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

    【讨论】:

    • 嗨@codemine,我无法让您的示例工作。我不确定我的代码中是否遗漏了一些东西。你用的ngx-mqtt版本是什么?
    • 亲爱的赫斯顿,如果你遇到的问题是在“提供:MqttService”这一行,这与他使用“ngx-mqtt”的事实有关:“^5.4.0”
    • 我可以发布但不能订阅..任何帮助
    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 2014-04-16
    • 1970-01-01
    • 2020-08-26
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多