> For the complete documentation index, see [llms.txt](https://docs.aic-eec.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.aic-eec.com/iot-development-with-infineon-psoc-tm-6-and-bdh-platform/bdh-iot-connectivity/mqtt.md).

# การเชื่อมต่อด้วย MQTT

MQTT (Message Queuing Telemetry Transport) เป็นโปรโตคอลที่ออกแบบมาสำหรับการส่งข้อความขนาดเล็กในเครือข่ายที่มีข้อจำกัดในด้านแบนด์วิดท์และพลังงาน เช่น ระบบ IoT ถูกพัฒนาเพื่อรองรับการส่งข้อมูลระหว่างอุปกรณ์ที่หลากหลาย

## **การใช้งาน MQTT ใน IoT**

* การเชื่อมต่อเซ็นเซอร์กับระบบคลาวด์: เซ็นเซอร์สามารถส่งข้อมูลไปยัง Broker ซึ่งจะกระจายข้อมูลไปยัง Subscriber ที่สนใจข้อมูลนั้น เช่น เซ็นเซอร์อุณหภูมิส่งข้อมูลไปยังคลาวด์
* การควบคุมอุปกรณ์ระยะไกล: แอปพลิเคชันสามารถส่งคำสั่งควบคุมไปยังอุปกรณ์ IoT ผ่าน MQTT เช่น การควบคุมเปิด/ปิดไฟในบ้าน
* การรวบรวมและวิเคราะห์ข้อมูล: ข้อมูลจากอุปกรณ์หลายตัวสามารถรวบรวมและส่งไปยังเซิร์ฟเวอร์กลางเพื่อการวิเคราะห์ เช่น การเก็บข้อมูลจากเซ็นเซอร์หลายตัวในโรงงานเพื่อตรวจสอบประสิทธิภาพการทำงาน

<figure><img src="https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MClo3nC-1US0rbK8Qau%2Fuploads%2FUuXI2zATN8xK9uwOhrxs%2Fimage.png?alt=media&amp;token=644816a9-d66b-4b6c-8714-f2fc6db42c1b" alt=""><figcaption></figcaption></figure>

## การสร้าง MQTT Broker และ Client

**ขั้นตอน Workshop**

1\. สร้าง folder ชื่อว่า  mqtt-demo\
2\. เปิด folder ด้วยโปรแกรม vsCode และทำการสร้าง nodejs project ผ่าน termial โดยใช้คำสั่ง

`npm init -y`

3\. จะได้ไฟล์ชื่อว่า Package.json ใน folder\
4\. ทำการติดตั้ง Package ที่จะใช้งาน

`npm install mqtt aedes aedes-cli aedes-persistence aedes-persistence-level aedes-server-factory  --save`

5\.  สร้างไฟล์​ broker.js ใน folder และเพิ่ม Code ด้างล่าง

```java
const aedes = require("aedes")();
const server = require("net").createServer(aedes.handle);
const port = 1883;

// Handle events on the broker
aedes.on("client", (client) => {
  console.log(`Client Connected: ${client.id}`);
});

aedes.on("clientDisconnect", (client) => {
  console.log(`Client Disconnected: ${client.id}`);
});

aedes.on("subscribe", (subscriptions, client) => {
  console.log(
    `Client ${client.id} subscribed to topics: ${subscriptions
      .map((s) => s.topic)
      .join(", ")}`
  );
});

aedes.on("unsubscribe", (subscriptions, client) => {
  console.log(
    `Client ${client.id} unsubscribed from topics: ${subscriptions.join(", ")}`
  );
});

aedes.on("publish", (packet, client) => {
  if (client) {
    console.log(`Message from ${client.id}: ${packet.payload.toString()}`);
  }
});

// Start the server
server.listen(port, () => {
  console.log(`MQTT broker started and listening on port ${port}`);
});
```

6. สร้างไฟล์ client.js ใน folder และเพิ่ม Code ด้านล่าง และทำการเปลี่ยนค่าตัวแปร name ให้เป็นชื่อภาษาอังกฤษของตัวเอง

```java
const mqtt = require("mqtt");
// เชื่อมต่อไปยัง MQTT broker
const client = mqtt.connect("mqtt://localhost:1883");
// เมื่อเชื่อมต่อแล้ว
client.on("connect", () => {
  console.log("Connected to MQTT broker");
  // Subscribe หัวข้อที่ใช้ wildcard
  const name = "thinnaphat"; /* !! เปลี่ยนเป็นชื่อตัวเอง (ภาษาอังกฤษ) */
  const topic = `${name}/#`;
  // const topic = `${name}/+/temperature`;
  // const topic = `${name}/2ndfloor/#`;

  client.subscribe(topic, (err) => {
    if (!err) {
      console.log(`Subscribed to topic: ${topic}`);
    }
  });

  // ตัวอย่างการ publish ข้อความไปยังหัวข้อต่างๆ
  client.publish(`${name}/2ndfloor/temperature`, "24°C");
  client.publish(`${name}/2ndfloor/humidity`, "60%");
  client.publish(`${name}/1stfloor/temperature`, "22°C");
});

// รอรับข้อความที่มาจากการ subscribe
client.on("message", (topic, message) => {
  console.log(`Received message: '${message.toString()}' on topic: '${topic}'`);
});
```

7\. ทำการ Run Code broker.js และ client.js แยกกัน (แยก Terminal)

`node broker.js`

`node client.js`

<figure><img src="https://1856353139-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MClo3nC-1US0rbK8Qau%2Fuploads%2FqyHYShx06bYUl6wYpcMF%2Fimage.png?alt=media&amp;token=35ed963c-54f5-4951-9397-f50d285e98e2" alt=""><figcaption><p>หน้าจอการ Run Code</p></figcaption></figure>

จาก Code broker.js จะทำหน้าที่เป็น Broker ที่จะเป็นตัวกลางในการเชื่อมต่อและ client.js จะทำหน้าที่เป็น Client ที่จะทำการ Subscribe Topic ไว้ก่อน และทำการ Publish ข้อมูลไปยัง Broker และหากต้องการทดลองส่งข้อมูลไปยัง Topic อื่นๆ สามารถทำได้โดยเปลี่ยน Topic ใน Code ของไฟล์​ client.js
