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

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

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

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

<figure><img src="/files/tacsdkqaFtTNuJBh8hzM" 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="/files/kZHJtdvOUv1iebLZYRd7" alt=""><figcaption><p>หน้าจอการ Run Code</p></figcaption></figure>

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.aic-eec.com/iot-development-with-infineon-psoc-tm-6-and-bdh-platform/bdh-iot-connectivity/mqtt.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
