PythonでPLCデータをデータベースから取得・統合する方法
PLC(プログラマブル・ロジック・コントローラ)のデータをデータベースに保存し、Pythonを使ってデータを取得・分析・可視化したい場合、このガイドが役立ちます。
MySQL, PostgreSQL, SQLite, MongoDB などのデータベースとPythonを接続し、PLCデータを処理する方法を解説します。
ステップ 1: Pythonのデータベース接続ライブラリをインストール
まず、使用するデータベースに応じた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データベースに接続
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データベースに接続
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: PythonでPLCデータを処理
Pandasを使ってデータを整形
データをPandas DataFrame に変換すると、処理が簡単になります。
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センサーデータの可視化")
plt.legend()
plt.show()
ステップ 5: PLCデータをリアルタイムで取得
PLCデータを定期的に取得 するには、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: PLCデータをウェブダッシュボードに表示
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: 異常データのアラートを設定
温度や圧力が異常値を超えた場合に警告 を出すスクリプトです。
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データをデータベースから取得し、分析・可視化・アラート設定・ウェブ表示を行う方法 を説明しました。
この方法を使えば、工場の自動化システム、産業IoT、リアルタイムモニタリング にPythonを活用できます!🚀
Related Posts
- PythonとPLCデータを活用した産業プロセスの自動化
- วิธีการทำให้กระบวนการอุตสาหกรรมเป็นอัตโนมัติด้วย Python และข้อมูลจาก PLC
- How to Automate Industrial Processes with Python and PLC Data
- วิธีเชื่อมต่อและดึงข้อมูล PLC จากฐานข้อมูลด้วย Python
- How to Connect and Integrate PLC Data from a Database with Python
- デジタルツイン: 概要
- ทำความรู้จักกับ ดิจิทัลทวิน ( Digital Twin )
- Digital Twin: An Introduction
- Smart Factory หรือ Industry 4.0 คืออะไร ?
Articles
- PythonとPLCデータを活用した産業プロセスの自動化
- วิธีการทำให้กระบวนการอุตสาหกรรมเป็นอัตโนมัติด้วย Python และข้อมูลจาก PLC
- How to Automate Industrial Processes with Python and PLC Data
- วิธีเชื่อมต่อและดึงข้อมูล PLC จากฐานข้อมูลด้วย Python
- How to Connect and Integrate PLC Data from a Database with Python
- AIモデルの仕組みを理解する: すべての読者向けガイド
- ทำความเข้าใจการทำงานของโมเดล AI: คู่มือสำหรับทุกคน
- Understanding How AI Models Work: A Guide for All Readers
- 次世代のAI開発 オープンソースモデルを活用したカスタムAIアプリケーションの構築
- สร้างแอปพลิเคชัน AI ที่ปรับแต่งได้ตามต้องการด้วยโมเดลโอเพ่นซอร์ส
- Next-Gen AI Development: Build Custom AI Applications with Open-Source Models
- AI時代で価値がないと感じる?それはあなただけではありません
- รู้สึกไม่มีคุณค่าในยุค AI? คุณไม่ได้รู้สึกแบบนี้คนเดียว
- Feeling Valueless as a Developer in the Age of AI? You’re Not Alone.
- Generative AI と Multimodal Models の比較: 主な違いと応用
- เปรียบเทียบ Generative AI และ Multimodal Models: ความแตกต่างและการประยุกต์ใช้
- Comparing Generative AI and Multimodal Models: Key Differences and Applications
- RasaのPipelineとPolicyの設定: よりスマートなチャットボットを構築するためのガイド
- การปรับแต่ง Pipeline และ Policies ของ Rasa: คู่มือสำหรับการสร้างแชทบอทที่ชาญฉลาดขึ้น
Our Products
Related Posts
- PythonとPLCデータを活用した産業プロセスの自動化
- วิธีการทำให้กระบวนการอุตสาหกรรมเป็นอัตโนมัติด้วย Python และข้อมูลจาก PLC
- How to Automate Industrial Processes with Python and PLC Data
- วิธีเชื่อมต่อและดึงข้อมูล PLC จากฐานข้อมูลด้วย Python
- How to Connect and Integrate PLC Data from a Database with Python
- デジタルツイン: 概要
- ทำความรู้จักกับ ดิจิทัลทวิน ( Digital Twin )
- Digital Twin: An Introduction
- Smart Factory หรือ Industry 4.0 คืออะไร ?
Articles
- PythonとPLCデータを活用した産業プロセスの自動化
- วิธีการทำให้กระบวนการอุตสาหกรรมเป็นอัตโนมัติด้วย Python และข้อมูลจาก PLC
- How to Automate Industrial Processes with Python and PLC Data
- วิธีเชื่อมต่อและดึงข้อมูล PLC จากฐานข้อมูลด้วย Python
- How to Connect and Integrate PLC Data from a Database with Python
- AIモデルの仕組みを理解する: すべての読者向けガイド
- ทำความเข้าใจการทำงานของโมเดล AI: คู่มือสำหรับทุกคน
- Understanding How AI Models Work: A Guide for All Readers
- 次世代のAI開発 オープンソースモデルを活用したカスタムAIアプリケーションの構築
- สร้างแอปพลิเคชัน AI ที่ปรับแต่งได้ตามต้องการด้วยโมเดลโอเพ่นซอร์ส
- Next-Gen AI Development: Build Custom AI Applications with Open-Source Models
- AI時代で価値がないと感じる?それはあなただけではありません
- รู้สึกไม่มีคุณค่าในยุค AI? คุณไม่ได้รู้สึกแบบนี้คนเดียว
- Feeling Valueless as a Developer in the Age of AI? You’re Not Alone.
- Generative AI と Multimodal Models の比較: 主な違いと応用
- เปรียบเทียบ Generative AI และ Multimodal Models: ความแตกต่างและการประยุกต์ใช้
- Comparing Generative AI and Multimodal Models: Key Differences and Applications
- RasaのPipelineとPolicyの設定: よりスマートなチャットボットを構築するためのガイド
- การปรับแต่ง Pipeline และ Policies ของ Rasa: คู่มือสำหรับการสร้างแชทบอทที่ชาญฉลาดขึ้น