Миграция к асинку

This commit is contained in:
2026-01-22 00:37:52 +09:00
parent 19871d1234
commit 25e04889c2
2 changed files with 76 additions and 28 deletions

View File

@@ -3,8 +3,8 @@ import time
import configparser import configparser
import logging import logging
import socket import socket
import asyncio
import lib.lomka as lomka import lib.lomka as lomka
import serial_asyncio
class caser: class caser:
#добавить по умолчанию с конфигом #добавить по умолчанию с конфигом
@@ -42,14 +42,16 @@ class caser:
self.active_comport = serial.tools.list_ports.comports()[0] # объект порта (dummy) self.active_comport = serial.tools.list_ports.comports()[0] # объект порта (dummy)
self.controller_number: bytes = 1 self.controller_number: bytes = 1
self.connection : serial.Serial self.connection : serial.Serial
self.async_connection : tuple
# Определение базовых констант/команд # Определение базовых констант/команд
self.default_consts = {True: 17, self.default_consts = {True: 17,
False: 0, False: 0,
"INFO": 51, "INFO": 51,
"READ_HEADER": 128, "READ_HEADER": 128,
"MANIPULATE_HEADER": 138, "DEFAULT_MESSAGE_LENGTH": 5,
"RESPONSE_LENGHT": 5} "MANIPULATE_HEADER": 138,
"RESPONSE_LENGHT": 5}
def find_comport(self, some_open_ports : list): def find_comport(self, some_open_ports : list):
'''Находит и возвращает корректный comport (объект)''' '''Находит и возвращает корректный comport (объект)'''
@@ -81,27 +83,36 @@ class caser:
self.controller_number = hex(controller_number) self.controller_number = hex(controller_number)
def send_command(self, cell_number : int, command: int, async def send_command(self, cell_number : int, command: int,
bytes_count=15, header=138): bytes_count=15, header=138):
active_comport = serial.Serial(self.comport, baudrate=self.baudrate, timeout=2) try:
self.logger.info(f"Connected to {active_comport.name }") # active_comport = serial.Serial(self.comport, baudrate=self.baudrate, timeout=2)
reader, writer = await serial_asyncio.open_serial_connection(
url=self.comport,
baudrate=self.baudrate
)
self.logger.info(f"Connected to {self.comport}")
# 1 - header(8Ahex) (138dec), 2 - controller number(01), 3 - cell number(04), 4 - command(11), 5 - checksum(9E) # 1 - header(8Ahex) (138dec), 2 - controller number(01), 3 - cell number(04), 4 - command(11), 5 - checksum(9E)
# *4 - (11) - open, (00) - close # *4 - (11) - open, (00) - close
data = [int(header).to_bytes(1, 'little'), data = [int(header).to_bytes(1, 'little'),
int(self.controller_number, 16).to_bytes(1, 'little'), int(self.controller_number, 16).to_bytes(1, 'little'),
cell_number.to_bytes(1, 'little'), cell_number.to_bytes(1, 'little'),
command.to_bytes(1, 'little')] command.to_bytes(1, 'little')]
data_string = b'' data_string = b''
for i in data: for i in data:
data_string += i data_string += i
checksum = self.bc_calculator.xor_bcc(data_string) checksum = self.bc_calculator.xor_bcc(data_string)
data_string += checksum.to_bytes(1, 'little') data_string += checksum.to_bytes(1, 'little')
active_comport.write(data_string) writer.write(data_string)
return active_comport.read(bytes_count) return await reader.read(bytes_count)
except Exception as error:
self.logger.error(f"{error}")
def read_controller(self, cell_number : int, command=51, header=128): def read_controller(self, cell_number : int, command=51, header=128):
active_comport = serial.Serial(self.comport, baudrate=self.baudrate, timeout=2) active_comport = serial.Serial(self.comport, baudrate=self.baudrate, timeout=2)
@@ -172,12 +183,37 @@ class caser:
# return str(error) # return str(error)
pass pass
# async def create_async_connection(self):
# try:
# self.async_connection = await serial_asyncio.open_serial_connection(
# url=self.comport,
# baudrate=self.baudrate
# )
# self.logger.info(f"Async connection to {self.comport}")
# except Exception as error:
# self.logger.error(f"Async connection error: {error}")
# pass
#хочу асинхронности #хочу асинхронности
def watchdog(self): async def watchdog(self):
'''Слушает контролер в реальном времени и возвращает bytearray с событием''' '''Слушает контролер в реальном времени и возвращает bytearray с событием'''
try: try:
active_comport = serial.Serial(self.comport, baudrate=self.baudrate, timeout=2) reader, writer = await serial_asyncio.open_serial_connection(
self.logger.info(f" |WD| Connected to (as Watchdog) {active_comport.name }") url=self.comport,
baudrate=self.baudrate
)
try:
while True:
data = await reader.read(self.default_consts["DEFAULT_MESSAGE_LENGTH"])
if data:
self.logger.debug(f"Received: {data}")
return data
except Exception as error:
self.logger.error(f"{error}")
writer.close()
await writer.wait_closed()
except Exception as error: except Exception as error:
self.logger.critical(f"{error}") self.logger.critical(f"{error}")

18
main.py
View File

@@ -3,6 +3,8 @@ import logging
import configparser import configparser
import serial import serial
import socket import socket
import asyncio
import time
if __name__ == "__main__": if __name__ == "__main__":
#consts&confs #consts&confs
@@ -29,9 +31,19 @@ if __name__ == "__main__":
zxc.set_controller_number(1) zxc.set_controller_number(1)
zxc.set_port_device() zxc.set_port_device()
zxc.set_controller_capacity(18) zxc.set_controller_capacity(18)
# добавь *aargs # добавь *aargs
#print(zxc.READ_ALL_CELLS()) #print(zxc.READ_ALL_CELLS())
print(zxc.OPEN_ALL_CELLS_LEGACY(True)) #print(zxc.OPEN_ALL_CELLS_LEGACY(True))
# print(zxc.read_controller(1)) # print(zxc.read_controller(1))
# print(zxc.send_command(1, 17)) # print(zxc.read_controller(1))
# print(zxc.read_controller(1))
async def main(zxc):
print(await zxc.send_command(1, 17))
exit()
while True:
asyncio.run(main(zxc))