1.0.1 • Published 1 year ago

@ertantcalc/tscalc-mqtt v1.0.1

Weekly downloads
-
License
-
Repository
-
Last release
1 year ago

Services

About services

The services implemented here will be used by both server and client. So if you will add another service, please first check if the service will be used by both server and client. Otherwise, better to implement the service inside relevant folder( server or client). The application has only 1 service so far which is 'MessageHandler'. This service is defined below. If you will add another method to the service, feel free to do so.

MessageHandler

It provides an API for MQTT broker. The application currently uses HiveMQ as MQTT broker. We may change the MQTT broker later based on our needs by updating credentials.

HiveMQ provides a free MQTT broker. We are using credentials to connect to the MQTT broker. You can find the credentials inside messageHandler.ts file. Since this is used by client and will be exposed to browser, we did not use .env file.

There are 3 methods inside the messageHandler.ts service which are connect, sendMessage and subscribe.

connect This method is used to connect to the MQTT broker. sendMessage This method is used to send a message by a topic to MQTT broker. It should be used only for server operations. Please check server code for more details. subscribe This method is used to get message based on the topic from MQTT broker. It should be used only for client operations. Please check client code for more details.

Examples

SendMessage

// TypeScript
try {
  const mqttClient = new MessageHandler('mqtts', 8883);
  await mqttClient.connect();
  await mqttClient.sendMessage('topic', 'message');
} catch (err) {
  console.log(err);
}

Subscribe

// TypeScript
try {
  const mqttClient = new MessageHandler('wss', 8884);
  await mqttClient.connect();
  await mqttClient.subscribe('topic', (topic: string, message: string) => {
    console.log(message); // we can read the message sent on the topic mentioned.
  });
} catch (err) {
  console.log(err);
}
1.0.1

1 year ago

1.0.0

1 year ago