测试代码:
from time import sleep as sleep
import socket
import time
import threading
import struct# 生成线程
class MakeThreading(threading.Thread):def __init__(self, target, set_daemon=True):super().__init__()self._target = targetself.setDaemon(set_daemon)self.start()# 连接到服务器
def connect2server(ip, port):global srv_linkdisconnected = Truewhile True:if disconnected: # 如果无连接print(time.asctime()[4:-5], 'Connecting to server...')try:srv_link.connect((ip, port))disconnected = Falseprint(time.asctime()[4:-5], 'Server is connected :')breakexcept Exception as E:print(time.asctime()[4:-5], 'Server connection failed. Retry in 5 seconds', E)sleep(5)continue# 发送数据
def send_datas(cycle, quantity): # 发送数据的周期和发送次数global srv_link, send_data, srv_ip, srv_port, is_sendingn = 0while n < quantity:try:is_sending = Truesrv_link.sendall(send_data)is_sending = Falsesleep(cycle)n += 1except Exception as E:print(time.asctime()[4:-5], 'Failed to send data', E)srv_link.close()srv_link = socket.socket(socket.AF_INET, socket.SOCK_STREAM)connect2server(srv_ip, srv_port)is_sending = False continue# 接收数据
def receive_datas(length):global rcv_data, srv_link, is_receivedn = 0while True:try:rcv_data = srv_link.recv(length)is_received = Trueexcept Exception as E:print(time.asctime()[4:-5], 'Failed to receive data', E)is_received = Falsesleep(5)if __name__ == '__main__':srv_link = socket.socket(socket.AF_INET, socket.SOCK_STREAM)srv_ip = '192.168.14.100'srv_port = 2000send_data = b''rcv_data = b''is_sending = False # 发送中标志is_received = False # 接收到数据标志connect2server(srv_ip, srv_port)MakeThreading(lambda: send_datas(0.5, 100000))MakeThreading(lambda: receive_datas(1024))while True:# 发送的内容if not is_sending:send_int1 = 1234 # 第一个是整数send_float1 = 1280.03 # 第二个是浮点数send_float2 = 2668.98 # 第三个是浮点数send_data = struct.pack('>h', send_int1) # 构建发送报文send_data += struct.pack('>f', send_float1)send_data += struct.pack('>f', send_float2)if is_received:rcv_int1 = struct.unpack('>h', rcv_data[:2])rcv_float1 = struct.unpack('>f', rcv_data[2:6])rcv_float2 = struct.unpack('>f', rcv_data[6:10])print('Datas received:', rcv_int1, rcv_float1, rcv_float2)is_received = Falsetime.sleep(0.01)
PLCSIM创建仿真PLC
PLC程序在这里:https://download.csdn.net/download/xulibo5828/87941287?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168808709516782427442084%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168808709516782427442084&biz_id=1&utm_medium=distribute.pc_search_result.none-task-download-2~all~first_rank_ecpm_v1~rank_v31_ecpm-1-87941287-null-null.142^v88^insert_down1,239^v2^insert_chatgpt&utm_term=python与PLC通信的数据转换&spm=1018.2226.3001.4187.2