Angular – ngx-mqtt
Content
Sources
Starter-Code
If you want use this module you have to activate websockets in your broker! DirectLink for Mosquitto broker on a raspberry pi
// environment.ts
export const environment = {
production: false,
mqtt: {
server: 'your.broker.ip', // 192.168.1.105
protocol: "wss", // not in use here
port: 9001,
username: 'user', // remove user/password if you don't use it
password: 'password'
}
};
// app.module.ts
import { IMqttServiceOptions, MqttModule } from "ngx-mqtt";
import { environment as env } from '../environments/environment';
export const MQTT_SERVICE_OPTIONS: IMqttServiceOptions = {
hostname: env.mqtt.server,
port: env.mqtt.port,
path: '',
username: env.mqtt.username,
password: env.mqtt.password,
};
imports: [...
MqttModule.forRoot(MQTT_SERVICE_OPTIONS)
]
// your.page.html
Publish
// your.page.ts
import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { IMqttMessage, MqttService } from "ngx-mqtt";
@Component({
selector: 'your',
templateUrl: './your.page.html',
styleUrls: ['./your.page.scss'],
})
export class YourPage {
events: any[];
private deviceId: string;
private subscription: Subscription;
public message: string;
constructor(private _mqttService: MqttService) {
this.subscription = this._mqttService.observe('mqtt/demo').subscribe((message: IMqttMessage) => {
this.message = message.payload.toString();
console.log("MQTT-SUB: ", this.message)
});
}
public unsafePublish(topic: string, message: string): void {
this._mqttService.unsafePublish(topic, message, { qos: 1, retain: true });
}
public ngOnDestroy() {
this.subscription.unsubscribe();
}
publish() {
console.log("MQTT-Publish Button")
this.unsafePublish("mqtt/demo", "hello world!");
}
}

Snippets
Some snippets
functions
.clientId
.connect
.disconnect
.messages
.observables
.observe
.observeRetained
.onClose
.onConnect
.onEnd
.onError
.onMessage
.onOffline
.onPacketreceive
.onPacketsend
.onReconnect
.onSuback
.publish
.state
.unsafePublish
.clientId
// .clientId
console.log('clientId: ', this._mqttService.clientId); //client-tioynfa0zur
// mqtt.js
// clientId: 'client' + Math.random().toString(16).substr(2, 8)
.connect
// .connect
this._mqttService.connect();
// If you use hivemq
this._mqttService.connect({
hostname: 'broker.hivemq.com',
port: 8000,
path: '/mqtt',
clientId: '1234qwerasd2'
});
.disconnect
// .disconnect
this._mqttService.disconnect();
.messages
// .messages
// Thiss will console.log all messages with topic and payload
this._mqttService.messages
.subscribe(
message => {
console.log('topic: ', message.topic, 'message: ',new TextDecoder('utf-8').decode(message.payload));
}
);
.observables
// .observables
// console.log the subscribed topics as an array
console.log(this._mqttService.observables);
.observe
// .observe
this.mqttService.observe('demo/topic')
.subscribe((message: IMqttMessage) => {
this.msg = message;
console.log(new TextDecoder('utf-8').decode(message.payload));
});
// keep in-mind to unsubscribe!
.observeRetained
.observeRetained
.onClose
// .onClose
this._mqttService.onClose
.subscribe(
onClose => {
console.log('onClose: ', onClose);
}
);
.onConnect
// .onConnect
this._mqttService.onConnect
.subscribe(
onConnect => {
console.log('onConnect: ', onConnect);
}
);
.onEnd
.onEnd
.onError
// .onError
this._mqttService.onError
.subscribe(
onError => {
console.log('onError: ', onError);
}
);
.onMessage
// .onMessage
this._mqttService.onMessage
.subscribe(
onMessage => {
console.log('onMessage: ', onMessage);
}
);
.onOffline
// .onOffline
this._mqttService.onOffline
.subscribe(
onOffline => {
console.log('onOffline: ', onOffline);
}
);
.onPacketreceive
// .onPacketreceive
this._mqttService.onPacketreceive
.subscribe(
onPacketreceive => {
console.log('onPacketreceive: ', onPacketreceive);
}
);
.onPacketsend
// .onPacketsend
this._mqttService.onPacketsend
.subscribe(
onPacketsend => {
console.log('onPacketsend: ', onPacketsend);
}
);
.onReconnect
// .onReconnect
this._mqttService.onReconnect
.subscribe(
onReconnect => {
console.log('onReconnect: ', onReconnect);
}
);
.onSuback
// .onSuback
this._mqttService.onSuback
.subscribe(
onSuback => {
console.log('onSuback: ', onSuback);
}
);
.publish
.publish
.state
// .state
this._mqttService.state
.subscribe(
state => {
console.log('state: ', state);
}
);
// Code: 0 =
// Code: 1 =
// Code: 2 =
.unsafePublish
.unsafePublish
public unsafePublish(topic: string, message: string, QoS?: any, retain?: boolean): void {
if (typeof QoS == 'undefined') {
QoS = 0;
}
if (typeof retain == 'undefined') {
retain = false;
}
this._mqttService.unsafePublish(topic, message, { qos: QoS, retain: retain });
}
mqtt.js docs
direct From mqtt.js
Event 'connect'
function (connack) {}
Emitted on successful (re)connection (i.e. connack rc=0).
connack received connack packet. When clean connection option is false and server has a previous session for clientId connection option, then connack.sessionPresent flag is true. When that is the case, you may rely on stored session and prefer not to send subscribe commands for the client.
Event 'reconnect'
function () {}
Emitted when a reconnect starts.
Event 'close'
function () {}
Emitted after a disconnection.
Event 'disconnect'
function (packet) {}
Emitted after receiving disconnect packet from broker. MQTT 5.0 feature.
Event 'offline'
function () {}
Emitted when the client goes offline.
Event 'error'
function (error) {}
Emitted when the client cannot connect (i.e. connack rc != 0) or when a parsing error occurs.
The following TLS errors will be emitted as an error event:
ECONNREFUSED
ECONNRESET
EADDRINUSE
ENOTFOUND
Event 'end'
function () {}
Emitted when mqtt.Client#end() is called. If a callback was passed to mqtt.Client#end(), this event is emitted once the callback returns.
Event 'message'
function (topic, message, packet) {}
Emitted when the client receives a publish packet
topic topic of the received packet
message payload of the received packet
packet received packet, as defined in mqtt-packet
Event 'packetsend'
function (packet) {}
Emitted when the client sends any packet. This includes .published() packets as well as packets used by MQTT for managing subscriptions and connections
packet received packet, as defined in mqtt-packet
Event 'packetreceive'
function (packet) {}
Emitted when the client receives any packet. This includes packets from subscribed topics as well as packets used by MQTT for managing subscriptions and connections
packet received packet, as defined in mqtt-packet