วิธีเชื่อมต่อและดึงข้อมูล PLC จากฐานข้อมูลด้วย Python

February 4, 2025
วิธีเชื่อมต่อและดึงข้อมูล PLC จากฐานข้อมูลด้วย Python

หากคุณกำลังมองหาวิธี ดึงข้อมูลจาก PLC (Programmable Logic Controller) ที่เก็บในฐานข้อมูล และนำมาใช้งานใน Python เช่น MySQL, PostgreSQL, SQLite หรือ MongoDB คู่มือนี้จะช่วยให้คุณสามารถ เชื่อมต่อ ดึงข้อมูล และวิเคราะห์ข้อมูล ได้ง่าย ๆ


ที่เกี่ยวข้อง

ขั้นตอนที่ 1: ติดตั้งไลบรารีสำหรับเชื่อมต่อฐานข้อมูลใน Python

ก่อนอื่นให้ติดตั้งไลบรารีที่จำเป็นสำหรับการเชื่อมต่อฐานข้อมูล:

pip install pymysql psycopg2 sqlite3 pymongo sqlalchemy pandas
  • MySQL: pymysql
  • PostgreSQL: psycopg2
  • SQLite: sqlite3 (มาพร้อมกับ Python)
  • MongoDB: pymongo
  • ORM (ใช้กับหลายฐานข้อมูล): sqlalchemy

ขั้นตอนที่ 2: เชื่อมต่อ Python กับฐานข้อมูลที่เก็บข้อมูลจาก PLC

เชื่อมต่อ Python กับ MySQL

หาก PLC เก็บข้อมูลใน MySQL, ใช้ pymysql:

import pymysql

# เชื่อมต่อ MySQL
conn = pymysql.connect(
    host='localhost',
    user='root',
    password='yourpassword',
    database='plc_data'
)

cursor = conn.cursor()
cursor.execute("SELECT * FROM sensor_readings")
data = cursor.fetchall()

# แสดงข้อมูลจาก PLC
for row in data:
    print(row)

conn.close()

เชื่อมต่อ Python กับ PostgreSQL

หากใช้ PostgreSQL, ใช้ psycopg2:

import psycopg2

# เชื่อมต่อ PostgreSQL
conn = psycopg2.connect(
    host="localhost",
    database="plc_data",
    user="postgres",
    password="yourpassword"
)

cursor = conn.cursor()
cursor.execute("SELECT * FROM sensor_readings")
data = cursor.fetchall()

for row in data:
    print(row)

conn.close()

เชื่อมต่อ Python กับ SQLite

หากเก็บข้อมูลจาก PLC ลง SQLite, ใช้ sqlite3:

import sqlite3

# เชื่อมต่อ SQLite
conn = sqlite3.connect("plc_data.db")
cursor = conn.cursor()

cursor.execute("SELECT * FROM sensor_readings")
data = cursor.fetchall()

for row in data:
    print(row)

conn.close()

เชื่อมต่อ Python กับ MongoDB

หาก PLC เก็บข้อมูลใน MongoDB, ใช้ pymongo:

from pymongo import MongoClient

# เชื่อมต่อ MongoDB
client = MongoClient("mongodb://localhost:27017/")
db = client["plc_data"]
collection = db["sensor_readings"]

for record in collection.find():
    print(record)

ขั้นตอนที่ 3: ประมวลผลข้อมูลจาก PLC ด้วย Python

แปลงข้อมูลเป็น Pandas DataFrame

เมื่อดึงข้อมูลจากฐานข้อมูลแล้ว สามารถ ใช้ Pandas จัดการข้อมูล ได้ง่ายขึ้น:

import pandas as pd

df = pd.DataFrame(data, columns=["timestamp", "temperature", "pressure", "status"])
print(df.head())

ขั้นตอนที่ 4: แสดงข้อมูล PLC ด้วยกราฟใน Python

สร้างกราฟด้วย Matplotlib

ใช้ matplotlib วาดกราฟข้อมูลเซ็นเซอร์จาก PLC:

import matplotlib.pyplot as plt

df['timestamp'] = pd.to_datetime(df['timestamp'])
plt.plot(df['timestamp'], df['temperature'], label="Temperature")
plt.plot(df['timestamp'], df['pressure'], label="Pressure")
plt.xlabel("เวลา")
plt.ylabel("ค่าจากเซ็นเซอร์")
plt.title("กราฟข้อมูล PLC Sensor")
plt.legend()
plt.show()

ขั้นตอนที่ 5: อัปเดตข้อมูลอัตโนมัติจาก PLC (Real-Time)

หากต้องการ ดึงข้อมูลจาก PLC โดยอัตโนมัติทุก ๆ 10 วินาที, ใช้ schedule:

import schedule
import time

def fetch_plc_data():
    conn = pymysql.connect(host="localhost", user="root", password="yourpassword", database="plc_data")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM sensor_readings ORDER BY timestamp DESC LIMIT 10")
    data = cursor.fetchall()
    print("ข้อมูล PLC ล่าสุด:", data)
    conn.close()

# ดึงข้อมูลทุก 10 วินาที
schedule.every(10).seconds.do(fetch_plc_data)

while True:
    schedule.run_pending()
    time.sleep(1)

ขั้นตอนที่ 6: สร้าง Dashboard แสดงข้อมูล PLC ด้วย Flask

หากต้องการ แสดงข้อมูล PLC ผ่านเว็บแอปพลิเคชัน, ใช้ Flask:

from flask import Flask, render_template
import pymysql

app = Flask(__name__)

def get_plc_data():
    conn = pymysql.connect(host="localhost", user="root", password="yourpassword", database="plc_data")
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM sensor_readings ORDER BY timestamp DESC LIMIT 10")
    data = cursor.fetchall()
    conn.close()
    return data

@app.route("/")
def index():
    data = get_plc_data()
    return render_template("index.html", data=data)

if __name__ == "__main__":
    app.run(debug=True)

ขั้นตอนที่ 7: ตั้งค่าแจ้งเตือนเมื่อข้อมูลผิดปกติ

หากต้องการ แจ้งเตือนเมื่ออุณหภูมิหรือแรงดันสูงผิดปกติ, สามารถใช้ Python ตรวจจับเงื่อนไข:

for row in data:
    timestamp, temperature, pressure, status = row
    if temperature > 80:
        print(f"⚠️ แจ้งเตือน: อุณหภูมิสูงเกินที่ {timestamp}: {temperature}°C")
    if pressure > 100:
        print(f"⚠️ แจ้งเตือน: แรงดันสูงเกินที่ {timestamp}: {pressure} Pa")

สรุป

คู่มือนี้อธิบายวิธี เชื่อมต่อ Python กับฐานข้อมูล PLC, ดึงข้อมูลจากเซ็นเซอร์, ประมวลผลข้อมูลด้วย Pandas, แสดงผลด้วย Matplotlib, อัปเดตข้อมูลอัตโนมัติ, สร้าง Dashboard และ ตั้งค่าแจ้งเตือนเมื่อข้อมูลผิดปกติ

คีย์เวิร์ดสำหรับ SEO

  • ดึงข้อมูล PLC ด้วย Python
  • เชื่อมต่อ Python กับฐานข้อมูล PLC
  • อ่านข้อมูลจาก PLC ไปยังฐานข้อมูล
  • วิเคราะห์ข้อมูลจาก PLC ด้วย Python
  • สร้าง Dashboard แสดงข้อมูล PLC
  • Python กับ PLC Automation
  • แสดงผลข้อมูลจาก PLC ในเว็บแอป
  • เชื่อมต่อ Python กับ MySQL, PostgreSQL, SQLite, MongoDB สำหรับ PLC
  • อัปเดตข้อมูลจาก PLC แบบเรียลไทม์
  • แจ้งเตือนข้อมูลผิดปกติจาก PLC ด้วย Python

วิธีนี้สามารถช่วยให้คุณ ติดตาม วิเคราะห์ และทำงานกับข้อมูลจาก PLC ได้อย่างมีประสิทธิภาพ ในอุตสาหกรรมการผลิต, ระบบอัตโนมัติ และ IoT! 🚀

บทความล่าสุด

Ready to talk about your project?

Share goals and constraints. We'll assemble architects and engineers to move fast with you.

Get in touch