Setup a MQTT Broker with Angular and Aedes

491 Views Asked by At

I found this Example of a simple MQTT Broker on Stackoverflow:

Typescript / MQTT / Node - How to acces class member from a callback function?

But i get a Error, when I try to recreate it:

This expression is not callable:

this.aedes=aedes();

It says it can not find this function aedes(). What can be wrong with my code?

Code:

broker.ts

import * as aedes from 'aedes';
import * as net from 'net';

export class Broker {

    aedes: aedes.Aedes;
    broker: net.Server;
    port: number;

    constructor(port: number){
        this.aedes=aedes();
        this.broker = net.createServer(this.aedes.handle);
        this.port = port;
        this.broker.listen(this.port, () => {
            console.log('MQTT is listening.');
        });
    }
    
    /** 
     * This is a callback register function
     *
     * Callback function must have a signature of type : function(topic: string, payload: string)
     **/
    onMsgReceived(callback: {(topic: string, payload: string): void}){
        this.aedes.on('publish', (packet, client) => {
            if (packet.cmd != 'publish') return;
            callback(packet.topic, packet.payload.toString());
        });
    }

}

test.ts

export class Test {
    someVar: string;

    constructor() {
        this.onMsgReceivedCallback = this.onMsgReceivedCallback.bind(this);
    }

    onMsgReceivedCallback(topic: string, payload: string) {
        console.log(`someVar: ${this.someVar}`);
    }
}

main.ts

import { Broker } from './broker'
import { Test } from './test'

console.log("main.ts");

const broker = new Broker(1883);
const broker2 = new Broker(4340);
const test   = new Test();


broker.onMsgReceived(test.onMsgReceivedCallback);

Thank you for your help!

1

There are 1 best solutions below

0
On

I faced a similar issue and was able to resolve it using the following change:

constructor(port: number){
        // this.aedes=aedes();
        this.aedes = aedes.Server();

        this.broker = net.createServer(this.aedes.handle);
        this.port = port;
        this.broker.listen(this.port, () => {
        console.log('MQTT is listening.');
    });
}