我正在制作一个python应用程序,该应用程序需要从多个串行端口接收和写入数据。所有这些都可以在单个端口上正常运行,但是在2个或更多端口上停止读写。
我有一个.py文件,可以处理所有“业务逻辑”,包括串行端口。它基本上打开了串行并继续寻找数据。我的问题是使此代码适合2个COM端口。我已经读过但无法实现的东西是子进程,显然我得到的示例代码是针对Python 2的,我不知道。
这是我的带有业务逻辑的.py文件:
thread_id = 0
main_loop = loop_model.loop(thread_id, port)
main_loop.get_serial_instance()
main_loop.open_port()
while (True):
main_loop.loop_by()
main_loop.close_serial()
这是我尝试过的:
from subprocess import Popen, PIPE
schedule_sytem_port = input("Insira a porta do Arduino para o sistema de agendamento\n")
entry_sytem_port = input("Insira a porta do Arduino para o sistema de entrada\n")
thread_id = 0
p1 = Popen(['python', './loop_handler.py', schedule_sytem_port], stdin=PIPE, stdout=PIPE, stderr=PIPE) # read COM1 permanently
p2 = Popen(['python', './loop_handler.py', entry_sytem_port], stdin=PIPE, stdout=PIPE, stderr=PIPE) # read COM2 permanently
while(True):
pass
如果需要的话,我将在这里留下我的“ loop_model”文件:
class loop():
ser = None
entry_ser = None
thread_id = 0
port = ''
def __init__(self, thread_id, port):
self.thread_id = thread_id
self.port = port
def get_serial_instance(self):
#instância da classe "serial"
try:
self.ser = serial.serial_handling()
except:
print("Não foi possível criar uma estância da porta serial de agendamentos, passando...")
pass
def open_port(self):
if (self.ser.is_open() == False):
self.ser.open_serial(self.port) #Abre a comunicação com a porta
print("Opening COM port", self.port)
def loop_by(self):
char = self.ser.has_input() #Verfica se há alguma entrada na porta serial
self.ser.write("oi".encode("latin-1"))
if (char != ''): #Se houver algo, trate-o
#print(char)
self.thread_id += 1
json_string = self.ser.get_input(char) #recupera toda a entrada, como JSON
print(json_string)
new_thread = threads.myThread(self.thread_id, "thread :" + str(self.thread_id), self.port)
values = self.ser.decode_json(json_string) #recupera os valores dentro do JSON
#Realiza a sequência de validação de agendamento
try:
print("Iniciando Thread")
new_thread.start()
print(values[0])
if (values[0] == 'agendamento'):
base_reply = "{\"Response\": \"?\"};;"
pode_agendar = agendamento.validar_agendamento(values[1], values[4], values[5])
#Se o agendamento for válido, agende :P
if (pode_agendar):
del values[0]
print(values)
list_reply = [" {\"agendamento\": {\"pino\": ?,; ", " \"horario_inic\": \"?\",; ", " \"horario_final\": \"?\",; ", " \"horario_atual\": \"?\"}};;"]
response_values = agendamento.agendar(values) #Passa para o método de agendamento, os valores do agendamento
for i in range(len(response_values)):
print(list_reply[i])
base_reply = (list_reply[i]).replace('?', str(response_values[i]), 1)
print(base_reply)
self.ser.write((base_reply).encode('latin-1'))
time.sleep(0.5)
#print(base_reply);
else:
base_reply = (base_reply + str('\n')).replace('?', "Failed", 1)
self.ser.write((base_reply).encode('utf-8'))
#time.sleep(10)
elif (values[0] == 'login'):
response = login.validar_login((values[1]))
base_reply = '{\"Response\": \"OK\", \"Id_Condomino\": ?, \"Coifas\": ?};;'
if (response != ''):
print(response)
for value in response:
print(value)
base_reply = (base_reply + str('\n')).replace('?', str(value), 1)
print(base_reply)
self.ser.write((base_reply).encode('utf-8'))
print("Logado")
else:
self.ser.write("{\"Response\": \"Failed\"};;".encode('utf-8'))
print("Usuário inválido")
elif (values[0] == 'entrada'):
print("Validando entrada")
print(values[1])
values[1] = str(values[1])
values[1] = values[1].replace(" ", "")
values[1] = "'" + values[1] + "'"
validacao = entrada.validar_entrada(values[1])
if (validacao != ''):
self.ser.write("Y;;".encode('utf-8'))
print("Acesso liberado")
time.sleep(0.5)
visita_tipo = validacao[0]
visita_tipo = visita_tipo.join("''")
visita_id = validacao[1]
is_saida = entrada.verificar_entrada_saida(visita_id)
horario = datetime.now().strftime('%d/%m/%Y %H:%M:%S')
if (is_saida):
entrada.update_visita(visita_id, (horario, ''))
else:
if (len(values[1]) == 6):
values = (visita_id, visita_tipo, horario, 0, values[1])
else:
values = (visita_id, visita_tipo, horario, values[1], 0)
response = entrada.inserir_visita(values)
else:
self.ser.write("N;;".encode('utf-8'))
print("Acesso negado")
finally:
new_thread.close()
while not(new_thread.escaped_flag):
pass
#ser.open_serial(port) #Abre a comunicação com a porta serial
print("Thread fechado")
self.thread_id = 0
def close_serial(self):
self.ser.close()
self.entry_ser.close()
我期望它能像读取和写入串行端口一样,但是具有多个端口。当我运行“子进程”代码时,程序可以正常运行,但是当我使用Putty检查端口时,它为空。