Establishing MQTT Connection in Ionic 3

I am facing a challenge with implementing Publish-Subscribe methods in my Ionic 3 application.

After consulting the information on this page, I attempted to link MQTT with my Ionic 3 application.

Can anyone guide me on how to successfully connect MQTT with an Ionic 3 application? What steps should I follow for a seamless connection?

To start, I installed the ng2-mqtt service by running the following command:

npm install ng2-mqtt --save

Below are snippets of the code I have written:

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

Despite following this setup, I am still experiencing issues with the implementation.

I would greatly appreciate any suggestions or changes that can help me overcome this challenge. I am currently stuck and seeking assistance.

Answer №1

After experimenting with various options, I stumbled upon this solution which utilizes a library for integrating MQTT into your project.

To get started, simply run npm install ngx-mqtt --save

Instructions: 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)
  ]

Next, you can incorporate it into your page like so: (e.g. home.ts file)

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

For further details on this library: https://github.com/sclausen/ngx-mqtt

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Need help: Autocomplete feature not working for two fields

I am currently working on implementing an autocomplete feature on two textboxes. The idea is that when a value is selected in one of the textboxes, another value should automatically appear in the other textbox. To better illustrate this concept, let me pr ...

Using jQuery's .live('click') method will only bind to the initial element found on the webpage

I developed a custom jQuery plugin that attaches to 8 different elements on a webpage. Within each element, I intended to utilize the .live() method to bind a click event to a link, triggering a form submission via ajax. However, I encountered an issue whe ...

Service injection results in an error

I am encountering an issue while trying to inject a service into a component, and the error message I receive is as follows: EXCEPTION: TypeError: Cannot read property 'getDemoString' of undefined It appears that the service is not being prop ...

Ways to refresh the main frame

Here is an example of parent code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Parent</title> </head> <body> <iframe src="https://dl.dropboxusercontent.com/u/4017788/Labs/child.html" width ...

Having trouble with a switch statement in Javascript that is unable to find a case for "none."

In my code, I am checking to see if there is a ball in a specific map point and then changing the color of the pixels where the ball is located to match the color of the ball. Here is my code snippet: function UpdateColorInMapPoints(mapPointIndexs) { / ...

Checking and contrasting dates within Javascript

Looking to compare two dates with different formats: a) Date1 - 01 Feb 2019 b) Date2 - 2/3/2017 It's important to account for invalid dates and ensure that Date1 is greater than Date2. function CompareAndValidateDates() { var Date1 ="01 Feb 20 ...

The server tag is displaying an error due to incorrect formatting in the hyperlink data-binding section

I'm currently facing an issue with the formatting of my hyperlink. The text part of the hyperlink is working fine, which leads me to believe that the problem lies within the JavaScript. However, I am unable to pinpoint the exact issue. <asp:Templa ...

The loading of content will happen only after the fadeOut effect

I'm attempting to incorporate content loading between fadeOut and fadeIn. When I execute the code below, the content loads before the fadeOut is complete: $("#contentArea").fadeOut(1000); $("#contentArea").promise().done(); $("#contentArea").load(c ...

Navigating collisions in the ECS architecture: Best practices

I'm currently developing a game using typescript and the ECS design pattern. One of the challenges I'm facing is handling collisions between different entities within the game world. I have an entity called Player which comprises several componen ...

It is imperative that the 'Access-Control-Allow-Origin' header value in the response is not set to '*' when the request's credentials mode is 'include'

I am currently working on establishing a connection using socket.io between Angular and a Node.js Server Within Angular, I have set up a new socket by importing socket.io-client and connecting it as follows: import * as io from 'socket.io-client& ...

Utilizing AngularJS to iterate over a single extensive unordered list

In my current Angular app, the JSON structure is as follows: 0: Object $$hashKey: "004" Date: "2014-04-17" Items: Array[3] 1: Object $$hashKey: "005" Date: "2014-04-18" Items: Array[3] 2: Object $$hashKey: "006" ...

Debugging in Javascript involves pausing or breaking at every instance of a javascript function being called

I am currently working on unraveling a complex legacy JavaScript codebase, and I'm finding it challenging to determine where to place breakpoints (having to locate the files and set a breakpoint in Firebug, etc). Is there a way for Firebug to automat ...

Fixed position toolbar within a container positioned beside a dynamically sized sidebar navigation

I'm trying to figure out how to create a fixed toolbar that fills the remaining width of the page when a side nav is collapsible. Setting the width to 100% causes it to overflow the page due to the dynamic nature of the side nav. Using calc() isn&apos ...

Tips for checking dropzone functionality during development

I'm currently working on an Angular 5 application and incorporating dropzonejs (the angular wrapper) into it. However, as I am not the backend developer, I do not have full visibility into how the backend has been developed. Currently, CORS is being ...

Limiting the types of files a user can access through a web browser

Hey there! I have a unique question that sets it apart from others, as it involves restricting file types for users with a browser popup. My goal is to prevent users from selecting certain file types before they choose a file. I've come across some s ...

Utilizing Express Routes to specify React page components

Currently, as I delve into the world of learning Express.js, I find myself faced with a unique scenario involving 2 specific URLs: /security/1 /security/2 As per the requirements of these URLs, the expected response will vary. If the URL is "/securi ...

Enhance the volume of an item within an array using JavaScript, React, and RecoilJS

When I check the console, the result is correct. However, when I try to replace that array in setCart, it doesn't work. This is using RecoilJS. const cartState=[ { id:1, productName:'Apple',price:100,quantity:1}, { id:2, productName: ...

Guide to toggling the anchor tag functionality as a button with JavaScript

I am trying to dynamically enable or disable an anchor tag that is used as a button using JavaScript. Within a certain condition, I want to control the state of this button. Here is the specific button in question: <div class="row my-2 text-right& ...

To properly display text strings in your application, ensure they are enclosed within a <Text> component in React Native. This is crucial

I recently integrated the react-native-login-screen package into my React Native project. Below is the code snippet that I used: import React, { Component } from "react"; import { Text, StyleSheet, View, Button, TouchableOpacity } from "reac ...

Injecting Services Error in Angular

I'm in the process of developing a web App and recently put together a new service: import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class ModuleService { constructor(private startTime: ...