製造業現場設備通訊多用底層通訊協議,opc是普通使用的一種。
Python多用於數據分析等互聯網領域,在opc通訊方面的資料、應用好像不多。不過不多不等於沒有,也不等於落後。
GitHub上的開源項目,FreeOPCUa 就是一個支持Python2,3 opc-ua 協議的實現。注意,這裏支持的是opc-ua協議,老的DA協議不支持;Kepserver 從 5.x 以後才支持opc-ua。
其實 FreeOPCUa 裏既能提供 client 端實現,也有 server 端以供測試或者真實使用。
from opcua import Client
class SubHandler(object):
"""
Client to subscription. It will receive events from server
"""
def datachange_notification(self, node, val, data):
# print("Python: New data change event", node, val)
print("changed. new value is : ", val)
def event_notification(self, event):
print("Python: New event", event)
def test2():
client = Client("opc.tcp://127.0.0.1:49321")
client.connect()
root = client.get_root_node()
aa = client.get_node('ns=2;s=Channel8.Device1.aa')
handler = SubHandler()
sub = client.create_subscription(1000, handler)
sub.subscribe_data_change(aa)
if __name__ == '__main__':
test2()
以上就是一個煎蛋實現,沒錯,就是如此的簡潔~
這裏有幾個準備工作:
1、在kepserver裏設置一個變量,按照代碼中格式將其定位;
2、查看/設置 kepserver 的opc-ua 的地址,與代碼中對應;
就可以 run 一下咯。