Files
pig-house-controller/main.py
2025-10-13 14:35:20 +08:00

90 lines
2.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
程序主入口 (双线程生产者-消费者模型)
主线程 (生产者):
- 职责以最高优先级不间断监听LoRa数据并将数据包放入任务队列。
- 特点永远不执行耗时操作保证LoRa数据接收的实时性。
工作线程 (消费者):
- 职责:从任务队列中取出数据包,并进行耗时的业务处理。
- 特点:可能会长时间阻塞,但不影响主线程的数据接收。
"""
import time
import _thread
from app.config import config
from app.uqueue import Queue # 导入我们自己创建的本地uqueue模块
# 导入接口和实现
from app.lora.lora_mesh_uart_passthrough_manager import LoRaMeshUartPassthroughManager
from app.bus.rs485_manager import RS485Manager
from app.processor import Processor
# 导入工作线程的执行函数
from app.worker import worker_task
from app.logs.logger import log
# --- 模块级变量定义 (带有类型提示) ---
lora_manager: LoRaMeshUartPassthroughManager | None = None
bus_manager: RS485Manager | None = None
processor: Processor | None = None
task_queue: Queue | None = None
def setup():
"""
初始化函数,负责创建所有对象实例、共享队列,并启动工作线程。
"""
global lora_manager, bus_manager, processor, task_queue
log("--- 系统初始化开始 ---")
# 1. 初始化硬件驱动和业务处理器
lora_manager = LoRaMeshUartPassthroughManager(config.LORA_CONFIG)
bus_manager = RS485Manager(config.BUS_CONFIG, config.DEFAULT_TIMEOUTS)
processor = Processor(lora_handler=lora_manager, bus_manager=bus_manager)
# 2. 从配置文件读取队列长度,并创建线程安全的队列
queue_size = config.SYSTEM_PARAMS.get('task_queue_max_size', 10)
task_queue = Queue(maxsize=queue_size)
log(f"任务队列已创建,最大容量: {queue_size}")
# 3. 启动工作线程
_thread.start_new_thread(worker_task, (task_queue, processor))
log("--- 系统初始化完成 ---")
def loop():
"""
主线程循环函数 (生产者)。
只负责监听LoRa并将数据放入队列。
"""
packet = lora_manager.receive_packet()
if packet:
if task_queue.full():
log("警告任务队列已满新的LoRa数据包被丢弃")
return
try:
task_queue.put_nowait(packet)
log(f"主线程新LoRa数据包已入队。当前队列大小: {task_queue.qsize()}")
except Exception as e:
log(f"错误:数据包入队失败: {e}")
time.sleep_ms(10)
# --- 程序主执行区 ---
if __name__ == "__main__":
setup()
log("--- 主线程进入循环 (LoRa监听) ---")
while True:
loop()