Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { Injectable } from '@angular/core';
- import { Observable } from 'rxjs/Observable';
- import { Observer } from 'rxjs/Observer';
- import { map, catchError } from 'rxjs/operators';
- import { Paho } from 'ng2-mqtt/mqttws31';
- import { Subject } from 'rxjs/Subject';
- // declare var Paho: any;
- @Injectable()
- export class MqttService {
- private _client: Paho.MQTT.Client;
- private mqtt_connect = new Subject<any>();
- private mqtt_pubsub_list = {}
- private d = new Date();
- private date = this.d.getTime();
- constructor() {
- // this.doConnect()
- }
- loginUser(username : any, password:any,callback) : Observable<any> {
- this._client = new Paho.MQTT.Client("digital-mrkt.tpfsoftware.com", Number("8884"), username+this.date.toString());
- console.log(this._client)
- this._client.onConnectionLost = (responseObject: Object) => {
- console.log(responseObject)
- console.log('Connection lost.');
- // this.doConnect()
- };
- this._client.onMessageArrived = (message: Paho.MQTT.Message) => {
- this.messageToTopic(message.destinationName, message.payloadString)
- };
- this._client.connect({
- onSuccess: this.onConnected.bind(this,callback),
- onFailure: this.onFailure.bind(this),
- userName: username,
- password: password,
- useSSL: true,
- cleanSession :true
- });
- return this.mqtt_connect.asObservable();
- }
- // doConnect() {
- // this._client.connect({
- // onSuccess: this.onConnected.bind(this),
- // userName: "backend",
- // password: "backend",
- // useSSL: true
- // });
- // }
- addSubscription(topic: string) {
- console.log(topic)
- this.mqtt_pubsub_list[topic] = new Subject<any>()
- this._client.subscribe(topic, {})
- }
- listenTopic(topic:string) : Observable<any> {
- this.mqtt_pubsub_list[topic] = new Subject<any>()
- this._client.subscribe(topic, {})
- return this._client[topic].asObservable();
- }
- private onConnected(callback){
- callback()
- this.mqtt_connect.next(true);
- console.log('Connected to broker.');
- }
- private onFailure(error): void {
- this.mqtt_connect.next(true);
- console.log('Error.',error);
- }
- messageToTopic(topic: any, message: string) {
- this.mqtt_pubsub_list[topic].next(message);
- }
- publishToTopic(topic: any, message: string) {
- this._client.send(new Paho.MQTT.Message(message))
- }
- getTopic(topic: string): Observable<any> {
- return this.mqtt_pubsub_list[topic].asObservable();
- }
- getConnection(): Observable<any> {
- if (this._client.isConnected()) {
- this.mqtt_connect.next(true);
- }
- return this.mqtt_connect.asObservable();
- }
- unSubscribeTopic(topic: string) {
- this._client.unsubscribe(topic, {})
- this.mqtt_pubsub_list[topic] = null;
- console.log("deleted", this.mqtt_pubsub_list[topic])
- }
- }
Add Comment
Please, Sign In to add comment