modbus_MediaPipe/PLC_to_Web.py

26 lines
886 B
Python

import asyncio
from pymodbus.server import StartAsyncTcpServer
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext
from pymodbus.datastore.store import ModbusSequentialDataBlock
# 建立 HR 暫存區,從位址 1633 開始,總共 100 筆
store = ModbusSlaveContext(
hr=ModbusSequentialDataBlock(1633, [0]*100)
)
context = ModbusServerContext(slaves={255: store}, single=False)
async def read_loop():
while True:
# 從 HR address 1633 開始,讀取 3 筆資料
values = context[255].getValues(3, 1633, count=3)
print(f"PLC 寫入的資料: {values}")
await asyncio.sleep(1) # 每秒顯示一次
async def run_server():
asyncio.create_task(read_loop()) # 啟動背景讀取任務
await StartAsyncTcpServer(context, address=("169.254.11.130", 502))
if __name__ == "__main__":
asyncio.run(run_server())