我是Python新手。我有一個應用程序,我希望讀取一個Modbus輸入寄存器並每隔10秒將數據記錄到一個csv文件,但我猜這個時間段是不相關的。我可以讀取一個寄存器,我可以登錄到一個csv,我可以每隔10秒記錄一次csv,但我正努力按照正確的順序完成所有這些。讀取Modbus寄存器並登錄到csv
如何重新排列我的代碼以打開端口並記錄最新的寄存器值?此時代碼將打開一次端口,讀取該值,然後每隔10秒記錄相同的值。
# Code
import socket
import struct
import time
import csv
# Create a TCP/IP socket
TCP_IP = '169.254.84.141'
TCP_PORT = 502
BUFFER_SIZE = 0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((TCP_IP, TCP_PORT))
try:
# Ask user for Modbus options
unitId = 5
functionCode = 4
startRegister = 00
numRegister = 16
# Construct request packet
req = struct.pack('>3H 2B 2H', 0, 0, 6, int(unitId), int(functionCode), int(startRegister), int(numRegister))
sock.send(req)
# Calculate receipt packet buffer and structure
BUFFER_SIZE = (3*2) + (3*1) + (int(numRegister)*2)
rec = sock.recv(BUFFER_SIZE)
def setB():
global BH
BH = 'B' #1
def setH():
global BH
BH = 'H' #2
functionLookup = {
1 : setB, # Read Coils (1 byte)
2 : setB, # Read Input Discrete Registers (1 byte)
3 : setH, # Read Holding Registers (2 byte)
4 : setH # Read Input Registers (2 byte)
}
functionLookup[int(functionCode)]()
s = struct.Struct('>3H 3B %s%s' %(numRegister, BH))
data = s.unpack(rec)
# Wait a couple of seconds before disconnecting
time.sleep(2);
Tank1Vol = data[6]
Tank1 = "Tank 1 Volume"
Units = "Litres"
Tank1csv = Tank1, (Tank1Vol),(Units)
starttime=time.time()
while True:
print ("tick")
print (Tank1csv)
time.sleep(10.0 - ((time.time() - starttime) % 10.0))
with open("Tank Level.csv", "a") as TanksFile:
TanksFileWriter = csv.writer(TanksFile)
TanksFileWriter.writerow(Tank1csv)
TanksFile.close()
finally:
sock.close()
Units = "Litres"
Tank1 = "Tank 1 Volume"
print (Tank1,(Tank1Vol),(Units))`
我一直在玩弄這一點,並有花葯的想法。所以...我的python文件獲取我需要的所有信息並將其記錄到csv,我可以使用另一個文件來運行代碼。是否可以使用導入時間函數,並每10秒使用import myfile.py運行原始文件。我一直在玩這個主題,但它只運行一次代碼。 – PrimitiveSource