ในการพัฒนาระบบ Industrial IoT (IIoT) การสื่อสารระหว่างเครื่องจักรและระบบควบคุมถือเป็นหัวใจสำคัญ OPC UA (Open Platform Communications Unified Architecture) เป็นโปรโตคอลมาตรฐานที่นิยมใช้กันอย่างแพร่หลาย แต่หัวใจสำคัญที่จะทำให้ระบบตอบสนองได้อย่างรวดเร็วคือการทำ Event Handling ครับ
ทำไมต้องใช้ Event Handling ใน OPC UA?
แทนที่จะใช้วิธีการ Polling (การดึงข้อมูลซ้ำๆ ตามเวลาที่กำหนด) ซึ่งสิ้นเปลืองทรัพยากร การใช้ Event-driven architecture จะช่วยให้ Module ของเราทำงานเฉพาะเมื่อเกิดเหตุการณ์สำคัญเท่านั้น เช่น เมื่ออุณหภูมิสูงเกินกำหนด หรือสถานะเครื่องจักรเปลี่ยนจาก Idle เป็น Running
ตัวอย่างโค้ด: การสร้าง Event Handler ด้วย Node-opcua
ด้านล่างนี้คือตัวอย่างการเขียนโปรแกรมด้วยภาษา JavaScript (Node.js) เพื่อดักจับ Event จาก OPC UA Server:
const { OPCUAClient, AttributeIds, TimestampsToReturn } = require("node-opcua");
// 1. กำหนดค่าการเชื่อมต่อ
const endpointUrl = "opc.tcp://localhost:4840";
async function monitorEvents() {
const client = OPCUAClient.create({ endpointMustExist: false });
await client.connect(endpointUrl);
const session = await client.createSession();
const subscription = await session.createSubscription2({
requestedPublishingInterval: 1000,
requestedMaxKeepAliveCount: 20,
publishingEnabled: true
});
// 2. การสร้าง Event Filter เพื่อดักจับ Data Change
const itemToMonitor = {
nodeId: "ns=1;s=TemperatureSensor",
attributeId: AttributeIds.Value
};
const monitoringParameters = {
samplingInterval: 100,
discardOldest: true,
queueSize: 10
};
const monitoredItem = await subscription.monitor(
itemToMonitor,
monitoringParameters,
TimestampsToReturn.Both
);
// 3. Event Handling Logic
monitoredItem.on("changed", (dataValue) => {
console.log(" [EVENT] ค่าอุณหภูมิเปลี่ยนเป็น: ", dataValue.value.value);
// คุณสามารถใส่ Logic การแจ้งเตือนหรือบันทึก Log ได้ที่นี่
});
}
monitorEvents().catch((err) => console.log("Error:", err));
อธิบายการทำงาน
- Subscription: เปรียบเสมือนการลงทะเบียนขอรับข่าวสารจาก Server
- MonitoredItem: ระบุ Node หรือข้อมูลที่เราสนใจติดตาม
- Event Listener (.on("changed")): ส่วนที่จัดการกับข้อมูลเมื่อมีการเปลี่ยนแปลงเกิดขึ้นทันที (Real-time)
การปรับใช้ OPC UA Event Handling จะช่วยลด Bandwidth ในโครงข่ายโรงงานของคุณ และเพิ่มประสิทธิภาพให้ระบบ Automation ทำงานได้อย่างมืออาชีพมากขึ้น
การสื่อสารข้อมูล, ระบบอัตโนมัติ, โปรโตคอลอุตสาหกรรม, เขียนโปรแกรม
