Phase 2

Local MQTT Broker aur Node.js App banana

Is phase me hum local Mosquitto broker run karenge, ek chhota Node.js MQTT app banayenge, aur terminal me real-time publish/subscribe result dekhenge.

BrokerLocal MQTT server jo messages route karega.
TopicMessage ka address, jaise home/sensor/data.
PublisherJo data broker ko bhejta hai.
SubscriberJo topic ko sunta hai aur data receive karta hai.

Is phase ka output

Local machine par broker chalega, Node.js app broker se connect hoga, app fake sensor data publish karega, aur wahi app subscribe karke message receive bhi dikhayega.

1. MosquittoBroker start hoga on port 1883.
2. Node.js appmqtt package se broker connect karega.
3. Live outputTerminal me publish aur receive dono dikhenge.

Step 1: Mosquitto install karo

Mosquitto ek lightweight MQTT broker hai. Isko install karne ke baad hum local broker run kar sakte hain.

Windows

winget install Eclipse.Mosquitto

Agar winget available nahi hai, official installer use karo: https://mosquitto.org/download/

macOS

brew install mosquitto

Ubuntu / Debian

sudo apt update sudo apt install mosquitto mosquitto-clients -y

Check install

mosquitto -h mosquitto_pub --help mosquitto_sub --help

Step 2: Local broker start karo

Ek terminal broker ke liye rakho. Verbose mode me connection aur message logs clearly dikhte hain.

mosquitto -v

Agar Address already in use ya port busy error aaye, iska matlab port 1883 par broker already running hai. Ya to direct next step test karo, ya old broker ko stop karke fresh start karo.

macOS / Linux: port check

lsof -i :1883

macOS / Linux: stop process

# lsof output me LISTEN wali mosquitto row ka PID use karo kill PID_NUMBER # force stop only if normal kill does not work kill -9 PID_NUMBER

Windows: port check

netstat -ano | findstr :1883

Windows: stop process

taskkill /PID PID_NUMBER /F

Example: lsof -i :1883 me mosquitto ki LISTEN row ka PID 1234 dikhe, command chalegi kill 1234. Uske baad broker ko dubara mosquitto -v se start karo.

Step 3: Pehle command line se test karo

Node.js app banane se pehle ek basic publish/subscribe test karte hain. Isse broker ka kaam clear ho jayega.

Terminal 2: Subscriber

mosquitto_sub -h localhost -p 1883 -t demo/message -v

Terminal 3: Publisher

mosquitto_pub -h localhost -p 1883 -t demo/message -m 'Hello from MQTT' mosquitto_pub -h localhost -p 1883 -t demo/message -m 'Hello Yarana IoT Guru!'

Result: subscriber terminal me demo/message Hello from MQTT dikhega. Yahi MQTT ka core idea hai.

Agar terminal me dquote> aa jaye, iska matlab quote close nahi hua. Ctrl+C dabao aur command dubara single quotes ke saath run karo: -m 'Hello Yarana IoT Guru!'

Step 4: One-way live message test

Ab ek terminal se baar-baar message publish karenge aur doosre terminal me live receive dekhenge. Ye simple one-way communication hai.

Terminal 2: Receiver

mosquitto_sub -h localhost -p 1883 -t chat/room -v

Terminal 3: Sender

while true; do echo -n "Message: " read msg [ -z "$msg" ] && continue mosquitto_pub -h localhost -p 1883 -t chat/room -m "$msg" done

Sender terminal me jo bhi type karoge, receiver terminal me chat/room message format me show hoga.

macOS zsh me read -p use mat karo, warna read: -p: no coprocess aa sakta hai. Isliye prompt ke liye echo -n aur input ke liye simple read msg use kar rahe hain.

Step 5: Two-way chat test

Two-way communication me dono side ek topic ko sunte hain aur doosre topic par message bhejte hain.

Terminal A: Abhishek side

mosquitto_sub -h localhost -p 1883 -t chat/b -v & while true; do echo -n "Abhishek: " read msg [ -z "$msg" ] && continue mosquitto_pub -h localhost -p 1883 -t chat/a -m "$msg" done

Terminal B: Yarana side

mosquitto_sub -h localhost -p 1883 -t chat/a -v & while true; do echo -n "Yarana: " read msg [ -z "$msg" ] && continue mosquitto_pub -h localhost -p 1883 -t chat/b -m "$msg" done

Flow: Abhishek side chat/a par publish karega aur chat/b sunega. Yarana side chat/b par publish karega aur chat/a sunega.

Stop karne ke liye pehle Ctrl+C dabao. Agar background subscriber still running ho to jobs check karo aur kill %1 run karo.

Step 6: Node.js MQTT app banao

Ab ek simple Node project banate hain. Is app me same client subscribe bhi karega aur har 2 second me sensor data publish bhi karega.

mkdir phase2-node-mqtt-demo cd phase2-node-mqtt-demo npm init -y npm install mqtt
const mqtt = require("mqtt"); const brokerUrl = "mqtt://localhost:1883"; const topic = "home/sensor/data"; const client = mqtt.connect(brokerUrl); client.on("connect", () => { console.log("Connected to local MQTT broker"); client.subscribe(topic, (error) => { if (error) { console.error("Subscribe failed:", error.message); return; } console.log("Listening on topic:", topic); }); setInterval(() => { const payload = { deviceId: "sensor-01", temperature: Number((24 + Math.random() * 6).toFixed(1)), humidity: Number((45 + Math.random() * 15).toFixed(1)), createdAt: new Date().toISOString() }; client.publish(topic, JSON.stringify(payload)); console.log("Published:", payload); }, 2000); }); client.on("message", (receivedTopic, message) => { console.log("Received:", receivedTopic, message.toString()); }); client.on("error", (error) => { console.error("MQTT error:", error.message); });
node app.js

Broker message route karta hai. Node app message home/sensor/data topic par bhej raha hai, aur same topic ko sun bhi raha hai.

Step 7: Main points recap

Is phase me complete local MQTT flow ready ho gaya.

Quick reference

# Broker mosquitto -v # Subscribe mosquitto_sub -h localhost -p 1883 -t demo/message -v # Publish mosquitto_pub -h localhost -p 1883 -t demo/message -m 'Hello from MQTT' mosquitto_pub -h localhost -p 1883 -t demo/message -m 'Hello Yarana IoT Guru!' # One-way live message test mosquitto_sub -h localhost -p 1883 -t chat/room -v while true; do echo -n "Message: " read msg [ -z "$msg" ] && continue mosquitto_pub -h localhost -p 1883 -t chat/room -m "$msg" done # Two-way chat: Abhishek side mosquitto_sub -h localhost -p 1883 -t chat/b -v & while true; do echo -n "Abhishek: " read msg [ -z "$msg" ] && continue mosquitto_pub -h localhost -p 1883 -t chat/a -m "$msg" done # Two-way chat: Yarana side mosquitto_sub -h localhost -p 1883 -t chat/a -v & while true; do echo -n "Yarana: " read msg [ -z "$msg" ] && continue mosquitto_pub -h localhost -p 1883 -t chat/b -m "$msg" done # Stop background subscriber jobs kill %1 # Node app mkdir phase2-node-mqtt-demo cd phase2-node-mqtt-demo npm init -y npm install mqtt node app.js