Files
pig-house-controller/comms/base_comm.py
2025-09-07 15:46:10 +08:00

72 lines
1.5 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.

from abc import ABC, abstractmethod
from typing import Any, Callable, Optional
class BaseComm(ABC):
"""
通信接口抽象基类
定义所有通信模块需要实现的基本方法
"""
@abstractmethod
def connect(self) -> bool:
"""
建立通信连接
Returns:
bool: 连接是否成功
"""
pass
@abstractmethod
def disconnect(self) -> None:
"""
断开通信连接
"""
pass
@abstractmethod
def send(self, data: bytes, address: Optional[str] = None) -> bool:
"""
发送数据
Args:
data: 要发送的数据
address: 目标地址(可选)
Returns:
bool: 发送是否成功
"""
pass
@abstractmethod
def receive(self, timeout: Optional[float] = None) -> Optional[bytes]:
"""
接收数据
Args:
timeout: 超时时间(秒)
Returns:
bytes: 接收到的数据如果没有数据则返回None
"""
pass
@abstractmethod
def is_connected(self) -> bool:
"""
检查通信连接状态
Returns:
bool: 是否已连接
"""
pass
def set_callback(self, callback: Callable[[bytes], None]) -> None:
"""
设置数据接收回调函数
Args:
callback: 接收数据时调用的回调函数
"""
pass