项目场景:
mircopython 开发 Esp32
问题描述
提示:1、在使用Mircopython开发esp32时,想实现用串口0进行收发,比如用sscom发送配置指令给MCU,但是直接分配UART0串口资源,会报错。2、在使用python的Input会阻塞整个线程 3、如何解决input带来的问题?
原因分析:
提示:这里填写问题的分析:
1、这是因为串口0被用作log打印和烧录,所以不能直接配置
2、因为input是一个阻塞式的方式,当只有一个主线程的时候,调用此方法必须要输入回车换行才才能退出
3、可以使用多线程解决阻塞问题
解决方案:
提示:用python的input方法作为输入方式
import time
import json
import _threadclass ConfigManager:
def __init__(self, config_file="config.json"):
# Device configuration items
self.config = {
"Update_Url": None,
"Config_Timer": None,
"Log_Post_Timer": None,
"Ota_Timer":None ,
"SL651_Url": None,
"SL651_Mn": None,
"SL651_Type": None,
"SL651_Postmode": None,
"Scan_Timer": None,
"Cal_Timer":None ,
"Post_Timer": None,
"User": None,
"Password": None,
"SN": None,
"Type": None,
"Cfg_Verison": None,
"App_Version": None,
"UDP_IP":None ,
"UDP_PORT":None ,
"WIFI_NAME":None,
"WIFI_PASS":None
}
self.config_file = config_file
self.load_config()
self.in_configuration_mode = False # Flag to indicate if in configuration mode
def load_config(self):
""" Load configuration items from FLASH """
try:
with open(self.config_file, 'r') as f:
self.config = json.load(f)
for key, value in self.config.items():
print(f"{key}: {value}")
except OSError:
print("Configuration file does not exist, please configure.")
except Exception as e:
print("Error occurred while loading configuration:", str(e))def save_config(self):
""" Save configuration items to FLASH """
try:
with open(self.config_file, 'w') as f:
json.dump(self.config, f)
print("Configuration saved:")
for key, value in self.config.items():
print(f"{key}: {value}")
except Exception as e:
print("Error occurred while saving configuration:", str(e))def enter_configuration_mode(self):
print("Entering configuration mode, please enter relevant configurations...")
self.in_configuration_mode = True # Set to configuration modewhile self.in_configuration_mode:
config_input = input("Please enter configuration command: ").strip()
if config_input:
print("Received configuration command:", config_input)
if config_input.startswith("AT+"):
_, wait_deal_cmd = config_input.split('+', 1)
self.handle_command(wait_deal_cmd)
elif config_input.upper() == "EXIT":
print("Exiting configuration mode.")
self.in_configuration_mode = False # Exit configuration mode
else:
print("Invalid command, must start with AT+.")def handle_command(self, command):
try:
if '=' in command:
key, value = command.split('=', 1)
key = key.strip()
value = value.strip()
if key in self.config:
self.config[key] = value
print(f"Successfully set this configuration: {key} = {value}")
self.save_config()
else:
print("Unknown command:", key)
elif command == "RST":
print("Device rebooting...")
man
# Here you can add actual reboot logic
else:
print("Invalid command format, please check your input.")
except Exception as e:
print("Error occurred while processing command:", str(e))def input_thread(self):
""" Input handling thread function """
while True:
user_input = input("Please enter command: ").strip()
if "AT" in user_input and not self.in_configuration_mode:
self.enter_configuration_mode() # Enter configuration mode
else:
print("Input command:", user_input)def start(self, timeout=6):
print(f"Please enter AT within {timeout} seconds to enter configuration mode...")
_thread.start_new_thread(self.input_thread, ())start_time = time.time()
while True:
if time.time() - start_time > timeout:
if not self.in_configuration_mode: # Only exit if not in configuration mode
print("Timeout, AT command not entered, exiting program.")
break
time.sleep(1) # Sleep for one second to avoid CPU usage# Start the main program
# if __name__ == "__main__":
# config_manager = ConfigManager()
# config_manager.start()
# config=config_manager.config
# print(config)