83 lines
2.6 KiB
Python
83 lines
2.6 KiB
Python
![]() |
from configparser import ConfigParser
|
||
|
import os
|
||
|
|
||
|
|
||
|
class ConfigManager:
|
||
|
def __init__(self, ini_path="setup.ini"):
|
||
|
self.ini_path = ini_path
|
||
|
self.config = ConfigParser()
|
||
|
|
||
|
def read_config(self):
|
||
|
"""读取配置文件"""
|
||
|
if not os.path.exists(self.ini_path):
|
||
|
return None
|
||
|
self.config.read(self.ini_path, encoding='utf-8')
|
||
|
return self.config
|
||
|
|
||
|
def create_default_config(self,num):
|
||
|
"""创建默认配置"""
|
||
|
self.config.add_section('Serial_config')
|
||
|
self.config.set('Serial_config', 'port', 'None')
|
||
|
self.config.set('Serial_config', 'baudrate', '9600')
|
||
|
|
||
|
|
||
|
self.config.add_section('Modbus_config')
|
||
|
self.config.set('Modbus_config', 'funcode', 'F4')
|
||
|
self.config.set('Modbus_config', 'position', '5')
|
||
|
|
||
|
self.config.add_section('DisHex_config')
|
||
|
for i in range(num):
|
||
|
idx = f'{i:02}'
|
||
|
rowname = f'row{idx}'
|
||
|
self.config.set('DisHex_config', rowname, '|||||0')
|
||
|
|
||
|
self.config.add_section('Quick_config')
|
||
|
self.config.set('Quick_config', 'log_time', '10')
|
||
|
|
||
|
with open(self.ini_path, 'w', encoding='utf-8') as f:
|
||
|
self.config.write(f)
|
||
|
|
||
|
def get_dishex_row(self, row):
|
||
|
"""获取十六进制显示的行"""
|
||
|
idx = f'{row:02}'
|
||
|
return self.config.get('DisHex_config', f'row{idx}')
|
||
|
|
||
|
def set_dishex_row(self, row, value_str):
|
||
|
"""设置十六进制显示的行"""
|
||
|
idx = f'{row:02}'
|
||
|
self.config.set('DisHex_config', f'row{idx}', value_str)
|
||
|
with open(self.ini_path, 'w', encoding='utf-8') as f:
|
||
|
self.config.write(f)
|
||
|
|
||
|
def get_funcode(self):
|
||
|
"""获取功能码"""
|
||
|
return self.config.get('Modbus_config', 'funcode')
|
||
|
|
||
|
def get_position(self):
|
||
|
"""获取位置"""
|
||
|
return int(self.config.get('Modbus_config', 'position'))
|
||
|
|
||
|
def get_log_time(self):
|
||
|
"""获取日志时间"""
|
||
|
return int(self.config.get('Quick_config', 'log_time'))
|
||
|
|
||
|
def get_port(self):
|
||
|
"""获取串口"""
|
||
|
return self.config.get('Serial_config', 'port')
|
||
|
|
||
|
def get_baudrate(self):
|
||
|
"""获取波特率"""
|
||
|
return self.config.get('Serial_config', 'baudrate')
|
||
|
|
||
|
def set_port(self, port_str):
|
||
|
"""设置串口"""
|
||
|
self.config.set('Serial_config', 'port', port_str)
|
||
|
with open(self.ini_path, 'w', encoding='utf-8') as f:
|
||
|
self.config.write(f)
|
||
|
|
||
|
def set_baudrate(self, baudrate_str):
|
||
|
"""设置波特率"""
|
||
|
self.config.set('Serial_config', 'baudrate', baudrate_str)
|
||
|
with open(self.ini_path, 'w', encoding='utf-8') as f:
|
||
|
self.config.write(f)
|