Skip to content

Commit

Permalink
Create iot.js
Browse files Browse the repository at this point in the history
  • Loading branch information
KOSASIH authored Jul 22, 2024
1 parent 6b3d76c commit c44589c
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions routes/iot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import express from 'express';
import { MQTT } from 'qtt-connection';

const router = express.Router();
const mqtt = new MQTT('mqtt://localhost:1883');

router.post('/iot-device', (req, res) => {
const { deviceId, sensorData } = req.body;
mqtt.publish(`device/${deviceId}`, JSON.stringify(sensorData));
res.json({ message: 'Sensor data published' });
});

router.get('/iot-device/:deviceId', (req, res) => {
const deviceId = req.params.deviceId;
mqtt.subscribe(`device/${deviceId}`);
mqtt.on('message', (topic, message) => {
if (topic === `device/${deviceId}`) {
res.json(JSON.parse(message.toString()));
}
});
});

export default router;

0 comments on commit c44589c

Please sign in to comment.