|
要将 **Siemens S7-1500 PLC 的数据写入 PC 服务器的数据库**,需要三步操作流程:
---
### ✅ 总体架构示意:
```
[S7-1500 PLC] ⇄(OPC UA / S7通讯)⇄ [PC服务程序] ⇒ [数据库(如MySQL、SQL Server等)]
```
---
## 🚀 一、确定通信方式(推荐两种):
### ✅ **推荐方式:OPC UA → Python/C# 客户端 → 数据库**
* PLC将数据暴露为 OPC UA 变量;
* PC上写一个服务程序周期性读取这些变量;
* 将数据写入数据库。
---
## 🛠 二、示例:使用 Python 读取PLC数据并写入数据库(MySQL 为例)
### 1️⃣ 安装依赖
```bash
pip install opcua mysql-connector-python
```
---
### 2️⃣ Python代码示例
```python
from opcua import Client
import mysql.connector
from datetime import datetime
# OPC UA连接PLC
opc_client = Client("opc.tcp://192.168.0.1:4840")
opc_client.connect()
node = opc_client.get_node("ns=2;s=DB1.RealTemp") # 替换成你的变量地址
# MySQL连接
db = mysql.connector.connect(
host="localhost",
user="root",
password="yourpassword",
database="plc_data"
)
cursor = db.cursor()
# 循环读取并写入数据库
try:
while True:
value = node.get_value()
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
sql = "INSERT INTO plc_table (value, timestamp) VALUES (%s, %s)"
cursor.execute(sql, (value, timestamp))
db.commit()
print("写入成功:", value)
time.sleep(1) # 每秒采集一次
except KeyboardInterrupt:
print("终止采集")
finally:
opc_client.disconnect()
cursor.close()
db.close()
```
---
### 3️⃣ 数据库建表语句(MySQL)
```sql
CREATE DATABASE IF NOT EXISTS plc_data;
USE plc_data;
CREATE TABLE plc_table (
id INT AUTO_INCREMENT PRIMARY KEY,
value FLOAT,
timestamp DATETIME
);
```
---
## ✅ 可替代平台和语言:
| 平台 | 通信方式 | 数据库写入方式 |
| -------------- | ----------------------- | --------------------------- |
| Python | OPC UA / Snap7 | MySQL / PostgreSQL / SQLite |
| C# (.NET) | OPC UA SDK / S7.NetPlus | SQL Server / SQLite |
| Node.js | Snap7 模块 | MongoDB / MySQL |
| 工业平台如 Ignition | 内置OPC客户端 | 内置数据库功能 |
---
## ❗提示:
* **实时性要求高**?→ 你可以设置每500ms采集一次。
* **写入频率高**?→ 使用**批量插入**或**内存缓存**。
* **断线容错**?→ 加 `try...except` 捕获异常,自动重连。
|
|