Felix Dürrwald 9025a8e9eb
Some checks failed
CI / main (push) Failing after 5m8s
feat: Implement mqtt-gateway
2024-09-29 08:55:18 +02:00

37 lines
1.1 KiB
TypeScript

import { NextFunction, Request, Response } from 'express'
import { WSQuery } from '../types'
import { MqttClient } from 'mqtt/*'
import transformData from '../utils/transformData'
import { omit } from '../utils/object'
// Middleware to send data to MQTT server
const sendToMqtt =
(mqttClient: MqttClient, MQTT_TOPIC: string) =>
(req: Request, res: Response, next: NextFunction) => {
const { ID, ...params } = omit(
req.query as WSQuery,
'PASSWORD',
'action',
'realtime',
'rtfreq'
)
// Format the data to be sent to MQTT
const data = transformData(params)
// Send the data to the MQTT server
for (const [key, value] of Object.entries(data)) {
const topic = `${MQTT_TOPIC}/${ID}/${key}`
mqttClient.publish(topic, value.toString(), (err) => {
if (err) {
console.error('Failed to publish to MQTT:', err)
}
})
}
// Proceed to the next middleware
next()
}
export default sendToMqtt