Pre-release v1.0

This commit is contained in:
2026-01-23 00:34:28 +09:00
parent 25e04889c2
commit d43d90ac1e
7 changed files with 354 additions and 76 deletions

View File

@@ -1,6 +1,4 @@
import serial.tools.list_ports
import time
import configparser
import logging
import socket
import lib.lomka as lomka
@@ -28,7 +26,7 @@ class caser:
config.read(config_name)
self.device_hwid = config['DEFAULT']['device_hwid']
self.baudrate = config['DEFAULT']['baudrate']
self.controller_capacity = config['DEFAULT']['controller_capacity']
self.controller_capacity = int(config['DEFAULT']['controller_capacity'])
# узнать какое исключение вызывается конкретно, ибо нужно проверять каждое по отдельности
except:
@@ -41,8 +39,9 @@ class caser:
self.comport: str # только адрес
self.active_comport = serial.tools.list_ports.comports()[0] # объект порта (dummy)
self.controller_number: bytes = 1
self.connection : serial.Serial
#self.connection : serial.Serial
self.async_connection : tuple
self.instance_error_count : int = 0
# Определение базовых констант/команд
self.default_consts = {True: 17,
@@ -61,14 +60,6 @@ class caser:
if self.device_hwid in port.hwid:
self.logger.info(f"Found the correct port: {port.device}")
return str(port.device)
def set_controller_capacity(self, capacity: int):
'''Устанавливает количество доступных замков'''
#сделать автоматом
if capacity:
self.controller_capacity = capacity
else:
self.controller_capacity = 18
def set_port_device(self, port_device=None):
'''Устанавливает com port'''
@@ -84,13 +75,13 @@ class caser:
self.controller_number = hex(controller_number)
async def send_command(self, cell_number : int, command: int,
bytes_count=15, header=138):
bytes_count=5, header=138):
try:
# 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
)
baudrate=self.baudrate,
timeout=2)
self.logger.info(f"Connected to {self.comport}")
@@ -111,91 +102,124 @@ class caser:
writer.write(data_string)
return await reader.read(bytes_count)
except Exception as error:
raise error
async def read_controller(self, cell_number : int, command=51,
header=128, bytes_count=5):
try:
# 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}")
data = [header.to_bytes(1, 'little'),
int(self.controller_number, 16).to_bytes(1, 'little'),
cell_number.to_bytes(1, 'little'),
command.to_bytes(1, 'little')]
data_string = b''
for i in data:
data_string += i
checksum = self.bc_calculator.xor_bcc(data_string)
data_string += checksum.to_bytes(1, 'little')
writer.write(data_string)
return await reader.read(bytes_count)
except Exception as error:
raise error
async def open_cell(self, cell_number):
'''открывает замок по номеру'''
try:
result = []
answer = await self.send_command(cell_number=cell_number,
command=self.default_consts[True],
bytes_count=self.default_consts["RESPONSE_LENGHT"],
header=self.default_consts["MANIPULATE_HEADER"])
result.append({"CELL_NUMBER": cell_number,
"CURRENT_STATUS": True if answer[-2] == 17 else False if answer[-2] == 0 else None,
"FULL_ANSWER": answer})
return result
except Exception as error:
self.logger.error(f"{error}")
self.instance_error_count += 1
return str(error)
def read_controller(self, cell_number : int, command=51, header=128):
active_comport = serial.Serial(self.comport, baudrate=self.baudrate, timeout=2)
self.logger.info(f"Connected to {active_comport.name }")
data = [header.to_bytes(1, 'little'),
int(self.controller_number, 16).to_bytes(1, 'little'),
cell_number.to_bytes(1, 'little'),
command.to_bytes(1, 'little')]
data_string = b''
for i in data:
data_string += i
checksum = self.bc_calculator.xor_bcc(data_string)
data_string += checksum.to_bytes(1, 'little')
active_comport.write(data_string)
return active_comport.read(5)
def READ_ALL_CELLS(self):
async def READ_ALL_CELLS(self):
'''и возвращает состояние всех замков'''
try:
result = []
for i in range(0, self.controller_capacity - 1):
answer = self.send_command(cell_number=i,
command=self.default_consts["INFO"],
bytes_count=self.default_consts["RESPONSE_LENGHT"],
header=self.default_consts["READ_HEADER"])
for i in range(1, self.controller_capacity + 1):
answer = await self.send_command(cell_number=i,
command=self.default_consts["INFO"],
bytes_count=self.default_consts["RESPONSE_LENGHT"],
header=self.default_consts["READ_HEADER"])
result.append({"CELL_NUMBER": i,
"CURRENT_STATUS": True if answer[-2] == 17 else False,
"FULL_ANSWER": answer})
"CURRENT_STATUS": True if answer[-2] == 17 else False if answer[-2] == 0 else None,
"FULL_ANSWER": answer})
return result
except Exception as error:
self.logger.error(f"{error}")
self.instance_error_count += 1
return str(error)
def OPEN_ALL_CELLS_LEGACY(self, confirm : bool):
async def set_controller_capacity_unsafe(self, capacity: int = 0):
'''Устанавливает количество доступных замков'''
if capacity >= 0:
self.controller_capacity = capacity
# else:
# # target max capatity
# self.controller_capacity = 128
# result = await self.READ_ALL_CELLS()
# if isinstance(result, list):
# self.controller_capacity = len(result)
# self.logger.info(f"Controller capacity set to {self.controller_capacity}")
# else:
# self.logger.error("READ_ALL_CELLS() failed")
# return False
async def OPEN_ALL_CELLS_LEGACY(self, confirm : bool):
'''Открывает все замки вручную и возвращает состояние всех замков
Confirm - подтверждение операции'''
if confirm:
try:
result = []
for i in range(1, self.controller_capacity + 1):
answer = self.send_command(cell_number=i,
answer = await self.send_command(cell_number=i,
command=self.default_consts[True],
bytes_count=self.default_consts["RESPONSE_LENGHT"],
header=self.default_consts["MANIPULATE_HEADER"])
result.append({"CELL_NUMBER": i,
"CURRENT_STATUS": True if answer[-2] == 17 else False,
"CURRENT_STATUS": True if answer[-2] == 17 else False if answer[-2] == 0 else None,
"FULL_ANSWER": answer})
return result
except Exception as error:
self.logger.error(f"{error}")
self.instance_error_count += 1
return str(error)
else:
return 1
def set_controller_capacity(self, capacity=0) -> str:
async def set_controller_capacity(self, capacity=0) -> str:
'''Устанавливает количество доступных замков'''
if capacity != 0:
self.controller_capacity = capacity
return self.controller_capacity
else:
# тут должно быть автоматическое определение кол-ва замков на контроллере
# try:
# return self.send_command(0, self.default_consts[True],
# self.default_consts["MANIPULATE_HEADER"],
# bytes_count=self.controller_capacity)
# except Exception as error:
# return str(error)
pass
try:
# написать
count = await self.send_command(0, self.default_consts[True],
self.default_consts["MANIPULATE_HEADER"],
bytes_count=self.controller_capacity)
except Exception as error:
return str(error)
# 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
#хочу асинхронности
async def watchdog(self):
'''Слушает контролер в реальном времени и возвращает bytearray с событием'''
try:
@@ -212,9 +236,11 @@ class caser:
except Exception as error:
self.logger.error(f"{error}")
self.instance_error_count = self.instance_error_count + 1
writer.close()
await writer.wait_closed()
except Exception as error:
self.logger.critical(f"{error}")
self.instance_error_count = self.instance_error_count + 1