ในยุคของ Industrial IoT (IIoT) การเก็บข้อมูลจากเครื่องจักรเพื่อนำมาวิเคราะห์ย้อนหลังเป็นสิ่งสำคัญมาก บทความนี้จะสอนวิธีการสร้าง Historical Data Log จาก OPC UA Server โดยใช้ Python ซึ่งเป็นวิธีที่ยืดหยุ่นและเป็นที่นิยมที่สุดในปัจจุบัน
ทำไมต้องทำ Historical Data Log?
การมีข้อมูลย้อนหลังช่วยให้เราสามารถทำ Predictive Maintenance, วิเคราะห์ OEE (Overall Equipment Effectiveness) และตรวจสอบหาสาเหตุของปัญหา (Root Cause Analysis) ได้อย่างแม่นยำ
ขั้นตอนการเตรียมตัว
- ติดตั้ง Python 3.x
- ติดตั้งไลบรารี
opcua-asyncioและpandas - เข้าถึง OPC UA Server (เช่น Kepware, Prosys หรือ Simulation Server)
ตัวอย่าง Code Python สำหรับดึงข้อมูลและบันทึก Log
โค้ดด้านล่างนี้จะทำการเชื่อมต่อกับ OPC UA Server และดึงค่าจาก Node ที่กำหนดเพื่อบันทึกลงในไฟล์ CSV ทุกๆ 5 วินาที
import asyncio
from asyncua import Client
import pandas as pd
from datetime import datetime
url = "opc.tcp://localhost:4840/freeopcua/server/"
node_id = "ns=2;i=2" # เปลี่ยนตาม Node ID ของคุณ
async def save_data_log():
async with Client(url=url) as client:
print("Connected to OPC UA Server")
while True:
# อ่านค่าจาก Node
var = client.get_node(node_id)
value = await var.read_value()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# สร้าง DataFrame และบันทึกลง CSV
data = {"Timestamp": [timestamp], "Value": [value]}
df = pd.DataFrame(data)
# บันทึกแบบ Append (ต่อท้ายไฟล์)
df.to_csv('historical_data.csv', mode='a', index=False, header=not any(open('historical_data.csv')))
print(f"Logged: {timestamp} - {value}")
await asyncio.sleep(5) # เก็บข้อมูลทุก 5 วินาที
if __name__ == "__main__":
asyncio.run(save_data_log())
สรุปการทำงาน
การใช้ Python ร่วมกับ OPC UA ช่วยให้เราสามารถสร้างระบบ Data Logger ขนาดเล็กได้ด้วยตัวเอง โดยไม่ต้องพึ่งพา Software ราคาแพง ข้อมูลที่ได้ในรูปแบบ CSV สามารถนำไปต่อยอดใน Power BI หรือทำ Machine Learning ได้ทันที
OPC UA ไทย, เก็บข้อมูลย้อนหลัง, สอนเขียน Python, ระบบ IIOT
