thingsboard通过python直连下发数据到PLC simatc S7-200
准备设备
1、PLC simatc S7-200 一台
2、PC、Thingsboard服务器、Pycharm
3、pycharm安装的库有async-paho-mqtt-client 、 iottalk-paho-mqtt 、 paho-mqtt 、 pip 、 python-sanp7 、 setuptools
4、网线一根
代码如下:
import snap7
from snap7.util import *
import json
import paho.mqtt.client as mqtt
import tkinter as tk
# 服务器连接配置
borker = "172.18.3.231"
port = 1884
access = "001"
# 建立PLC连接通道
plc = snap7.client.Client()
# 定义Plc连接
def plc_connect(ip, rack, slot):
plc.connect(ip, rack, slot)
if plc.get_connected():
print("连接成功")
def qWrite1(byte, bit, value):
data = plc.read_area(snap7.types.Areas.PA, 0, byte, 1) # read_area的SIZE参数,这里默认位一个字节
set_bool(data, 0, bit, value)
plc.write_area(snap7.types.Areas.PA, 0, byte, data)
def qRead1(byte, bit):
data = plc.read_area(snap7.types.Areas.PA, 0, byte, 1)
print(get_bool(data, 0, bit))
# PLC断开连接
def plc_disconnect():
plc.disconnect()
def on_connect(client, userdata, flags, rc):
print("rc code:", rc)
if rc:
print("链接tb失败")
return
print("链接成功")
# 回调函数 订阅主题 'v1/devices/me/rpc/request/+'
client.subscribe('v1/devices/me/rpc/request/+')
def on_message(client, userdata, msg):
global temp
print('Topic: ' + msg.topic + '\nMessage: ' + str(msg.payload))
request_id = msg.topic.split('/')[-1]
print(request_id)
method = json.loads(msg.payload)['method']
try:
data = json.loads(msg.payload)['params']
if method == 'setValue':
print("收到遥测数据:", data)
client.publish('v1/devices/me/rpc/response/'+request_id,
json.dumps({"response": request_id}), 1)
if method == 'setIO':
print("收到遥信数据:", data)
set_config(data)
plc_connect('192.168.1.101', 0, 1)
qWrite1(0b00000000, 0, data)
plc_disconnect()
client.publish('v1/devices/me/rpc/response/' + request_id,
json.dumps({"response": request_id}), 1)
except Exception as e:
print(e)
pass
def set_config(value):
if value:
l.configure(bg="green", text='开')
else:
l.configure(bg="red", text='关')
window = tk.Tk()
window.title(u'测试tb下发的开关量')
window.geometry('400x300')
l = tk.Label(window, text='开', bg='green', font=('Arial', 12), width=30,height=12)
l.pack()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.username_pw_set(access)
client.connect(borker, port, keepalive=60)
try:
client.loop_start()
except KeyboardInterrupt:
client.disconnect()
window.mainloop()
实现效果为:
控制PLC的Q0.0的输出指示灯。