Skip to content

Instantly share code, notes, and snippets.

@AnthonyLzq
Created January 24, 2023 03:08
Show Gist options
  • Save AnthonyLzq/ff99d1dcff9e127dada42cfbca401c71 to your computer and use it in GitHub Desktop.
Save AnthonyLzq/ff99d1dcff9e127dada42cfbca401c71 to your computer and use it in GitHub Desktop.
Script to create a route to listen using MQTT
import { MqttClient } from 'mqtt'
import { UserServices } from 'services'
const PUB_TOPIC = 'DoorCloud'
const SUB_TOPIC = `\${PUB_TOPIC}/photo`
const sub = (client: MqttClient) => {
const subDebugger = 'DoorCloud:Mqtt:demo:sub'
client.subscribe(SUB_TOPIC, error => {
if (!error) console.log(`Subscribed to ${subDebugger}`)
})
client.on('error', error => {
console.error(error, `Topic: ${SUB_TOPIC} - Error`)
})
/**
* The message received will be a string in the following format:
* userID--format--base64Photo
*/
client.on('message', async (topic, message) => {
if (topic.includes('photo')) {
console.log('Received a photo')
const [userID, format, base64] = message.toString().split('----')
const [, base64Photo] = base64
.split(`data:image/${format};base64,`)
const us = new UserServices(log)
try {
await us.sendPhotoThroughWhatsapp(
userID,
format,
Buffer.from(base64Photo, 'base64')
)
console.log(`Topic: ${SUB_TOPIC} - Photo send.`)
} catch (error) {
const errorMessage = 'Error while sending the image to the user'
console.error(errorMessage, error)
throw new Error(errorMessage)
}
}
})
}
const demo: Route = {
sub,
PUB_TOPIC,
SUB_TOPIC
}
export { demo }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment