1. adafruit-circuitpython-typing:不是装饰,是嵌入式Python的“安全带”
在CircuitPython项目里写def read_sensor(i2c),运行时才报错AttributeError: 'str' object has no attribute 'scan'——这种翻车,我经历过三次。第一次以为是硬件接触不良,拆了板子重焊;第二次怀疑是库版本冲突,来回切了五版adafruit-busio;第三次才意识到:问题根本不在运行时,而在写函数签名那一刻就埋下了隐患。adafruit-circuitpython-typing包不是给IDE看的摆设,它是专为资源受限、无完整Python运行时的微控制器环境设计的类型提示系统——它让mypy静态检查能提前捕获90%以上的硬件接口误用,把“设备没响应”这类玄学问题,拦在烧录固件之前。它不改变运行逻辑,但强制你在编码阶段就厘清I2C总线、PWM引脚、ADC通道这些物理资源的契约关系。适合所有用CircuitPython做工业传感器采集、边缘控制或教育实验的开发者,尤其当你开始把多个传感器(BME280、ADS1115、PCA9685)挂到同一块Feather RP2040上时,这个包就是你硬件资源管理的“后悔药”。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 类型定义即契约:为什么必须用adafruit_typing而非标准typing
2.1 标准typing无法表达硬件语义,这是根本矛盾
Python标准库的typing模块提供List, Dict, Optional等泛型,但它对硬件外设毫无感知。比如,def init_device(bus)这个函数签名,静态检查器只能告诉你bus是个对象,却无法判断它是否具备.scan()方法、是否支持.frequency属性、甚至是否真的连着一根物理I²C线。而adafruit-circuitpython-typing中的I2C类型,其定义内嵌了CircuitPython底层驱动的接口契约:
python复制# 来自adafruit-circuitpython-typing源码(精简)
class I2C(Protocol):
def scan(self) -> List[int]: ...
@property
def frequency(self) -> int: ...
@frequency.setter
def frequency(self, value: int) -> None: ...
def try_lock(self) -> bool: ...
def unlock(self) -> None: ...
这个Protocol不是抽象基类,而是鸭子类型契约:任何对象只要实现了scan()和frequency,就被认为是合法的I2C实例。这与CircuitPython实际驱动(如busio.I2C)完全对齐。当你传入一个字符串"invalid",mypy立刻报错:
code复制error: Argument 1 to "init_i2c_device" has incompatible type "str"; expected "I2C"
而标准typing.Any或object则完全放行——直到运行时"invalid".scan()才炸。
提示:
adafruit_typing.I2C不是busio.I2C的子类,而是独立协议。这意味着你可以用它约束自定义模拟器(如用于单元测试的MockI2C),只要它满足协议,类型检查就通过。
2.2 硬件类型分层:从物理引脚到逻辑设备的映射链
adafruit-circuitpython-typing构建了一条清晰的硬件抽象链,每一层都对应真实的物理约束:
| 类型名 | 物理对应 | 关键契约方法/属性 | 典型误用场景 |
|---|---|---|---|
Pin |
MCU上的GPIO引脚(如board.D5) |
.value, .direction |
用board.LED当I2C时钟线(类型不匹配) |
DigitalInOut |
配置为输入/输出的引脚(需digitalio.DigitalInOut实例) |
.direction, .value, .pull |
直接传board.D5给需要DigitalInOut的函数(缺少.pull属性) |
I2C |
I²C总线控制器(如busio.I2C) |
.scan(), .frequency, .try_lock() |
传SPI总线对象进去(.scan()不存在) |
SPI |
SPI主控制器(如busio.SPI) |
.configure(), .try_lock(), .write() |
用board.SCK代替整个SPI对象(缺少传输能力) |
PWMOutput |
PWM输出通道(如pulseio.PWMOut) |
.duty_cycle, .frequency |
传普通数字引脚,试图设.duty_cycle(无此属性) |
AnalogIn |
ADC输入通道(如analogio.AnalogIn) |
.value, .reference_voltage |
用I2C设备地址(如0x48)当AnalogIn(类型完全错位) |
这个分层不是凭空设计,而是严格遵循CircuitPython硬件驱动的实际API。例如,PWMOutput.duty_cycle接受0-65535的整数,而AnalogIn.value返回0-65535的ADC原始值——两者数值范围相同,但语义截然不同。adafruit_typing用类型隔离了它们,避免你在调用set_pwm_duty_cycle(pwm, adc.value)时,因数值巧合而侥幸通过,却在真实硬件上输出错误占空比。
2.3 类型安全如何降低硬件调试成本:一个真实案例
某高校实验室开发温湿度监控节点,使用BME280(I²C)和DS18B20(单总线)。学生A写了如下代码:
python复制from adafruit_typing import I2C
def read_bme280(i2c_bus: I2C) -> dict:
# ... 实际读取逻辑
pass
# 错误:把单总线设备的引脚当I2C总线传入
bme_data = read_bme280(board.D4) # board.D4是DS18B20的单总线引脚
没有类型提示时,这段代码能“跑起来”,但BME280永远返回0值——因为board.D4对象没有.scan()方法,read_bme280内部调用i2c_bus.scan()直接抛出AttributeError,被静默吞掉。学生花了三天用逻辑分析仪查I²C波形,最终发现是软件传参错误。加上adafruit_typing.I2C后,mypy在保存文件瞬间就报错:
code复制error: Argument 1 to "read_bme280" has incompatible type "Pin"; expected "I2C"
调试时间从72小时压缩到5分钟。类型提示在这里不是“锦上添花”,而是把硬件连接错误提前转化为编译期错误,这是嵌入式Python区别于传统C开发的关键安全升级。
3. 八个实战案例:从初始化到多设备协同的类型化写法
3.1 I2C设备存在性检查:避免“设备未响应”的玄学黑洞
python复制from adafruit_typing import I2C
import busio
import board
def init_i2c_device(i2c: I2C, address: int) -> None:
"""初始化I2C设备:先扫描再操作,杜绝盲目通信"""
# 静态检查确保i2c有.scan()方法
if address not in i2c.scan():
raise ValueError(f"I2C device at {hex(address)} not found on bus")
# 此处可安全执行设备寄存器配置
print(f"✅ Initialized I2C device at {hex(address)}")
# 正确用法:传入真实的I2C总线实例
i2c_bus = busio.I2C(board.SCL, board.SDA)
init_i2c_device(i2c_bus, 0x76) # BME280地址
# 错误用法(mypy立即拦截):
# init_i2c_device("fake_bus", 0x76) # error: Argument 1 has incompatible type "str"
# init_i2c_device(board.SCL, 0x76) # error: Argument 1 has incompatible type "Pin"
参数说明:
i2c: I2C:强制要求传入符合I²C协议的对象,确保.scan()可用;address: int:设备7位地址(如0x76),类型为int而非str,避免"0x76"字符串误传;i2c.scan()返回List[int],类型系统保证address not in ...比较合法。
注意:
i2c.scan()在CircuitPython中可能因总线噪声返回空列表。本例假设硬件连接可靠,生产环境应增加重试逻辑,但类型契约不变。
3.2 数字引脚方向配置:防止输入/输出模式错配导致短路
python复制from adafruit_typing import DigitalInOut
import digitalio
import board
def configure_pin(pin: DigitalInOut, direction: digitalio.Direction) -> None:
"""安全配置数字引脚方向:类型约束确保pin已实例化且可设方向"""
# 静态检查确保pin有.direction属性
pin.direction = direction
print(f"🔧 Pin configured as {direction.name}")
# 正确:先创建DigitalInOut实例,再传入
led_pin = digitalio.DigitalInOut(board.LED)
configure_pin(led_pin, digitalio.Direction.OUTPUT)
# 错误(mypy拦截):
# configure_pin(board.LED, digitalio.Direction.OUTPUT) # error: Argument 1 has incompatible type "Pin"
# configure_pin(led_pin, "output") # error: Argument 2 has incompatible type "str"
关键点:DigitalInOut类型明确区分了“物理引脚”(Pin)和“已配置的IO通道”(DigitalInOut)。board.LED只是Pin,不能直接设.direction;必须用digitalio.DigitalInOut(board.LED)包装后,才获得完整的IO能力。类型系统在此处强制你完成这个必要步骤,避免因忘记实例化而导致AttributeError。
3.3 温度传感器抽象:统一接口屏蔽硬件差异
python复制from adafruit_typing import TemperatureSensor
from typing import Optional
class TemperatureMonitor:
def __init__(self, sensor: TemperatureSensor):
"""构造函数强制传入符合TemperatureSensor协议的传感器"""
self.sensor = sensor
self._last_temp: Optional[float] = None
def read_temperature(self) -> float:
"""读取温度:类型系统保证sensor有.temperature属性"""
# mypy确保sensor.temperature存在且返回float
self._last_temp = self.sensor.temperature
return self._last_temp
# 使用示例:BME280和TMP117都实现TemperatureSensor协议
# bme280 = adafruit_bme280.Adafruit_BME280_I2C(i2c_bus)
# tmp117 = adafruit_tmp117.TMP117(i2c_bus)
# monitor = TemperatureMonitor(bme280) # 或tmp117,类型检查均通过
# print(monitor.read_temperature())
类型契约:TemperatureSensor协议定义了.temperature: float属性。无论底层是I²C的BME280还是SPI的MAX31855,只要它们暴露该属性,就能被TemperatureMonitor无缝接纳。这让你在更换传感器时,无需修改业务逻辑,只需确保新传感器满足协议——类型系统就是你的适配器。
3.4 PWM占空比安全设置:数值范围校验与硬件映射
python复制from adafruit_typing import PWMOutput
from typing import Union
def set_pwm_duty_cycle(pwm: PWMOutput, duty_cycle: Union[int, float]) -> None:
"""设置PWM占空比(0-100%):类型+运行时双重防护"""
# 运行时校验:防止超出硬件允许范围
if not 0 <= duty_cycle <= 100:
raise ValueError("Duty cycle must be between 0 and 100")
# 类型系统确保pwm有.duty_cycle属性
# CircuitPython中duty_cycle是0-65535的整数
pwm.duty_cycle = int(duty_cycle * 65535 / 100)
# 正确:传入PWMOut实例
# pwm = pulseio.PWMOut(board.D5)
# set_pwm_duty_cycle(pwm, 75.5) # 75.5%占空比
# 错误(mypy拦截):
# set_pwm_duty_cycle(board.D5, 50) # error: Argument 1 has incompatible type "Pin"
# set_pwm_duty_cycle(pwm, "50") # error: Argument 2 has incompatible type "str"
参数设计逻辑:
duty_cycle: Union[int, float]:接受整数或浮点数,方便用户输入50或50.0;pwm.duty_cycle = int(...):将百分比映射到CircuitPython硬件要求的16位整数范围;- 运行时
if校验是最后一道防线,类型校验是第一道——二者缺一不可。
3.5 ADC多采样统计:类型安全的数据聚合
python复制from adafruit_typing import AnalogIn
from typing import Tuple
def read_adc_stats(adc: AnalogIn, samples: int = 10) -> Tuple[float, float]:
"""读取多次ADC值并返回平均值和最小值:类型确保adc.value可读"""
# mypy确保adc.value存在且返回int
readings = [adc.value for _ in range(samples)]
average = sum(readings) / samples
minimum = min(readings)
return (average, minimum)
# 使用:
# adc = analogio.AnalogIn(board.A0)
# avg, min_val = read_adc_stats(adc, samples=20)
# print(f"ADC Avg: {avg:.0f}, Min: {min_val:.0f}")
类型价值:AnalogIn.value返回int(0-65535),readings列表类型被推断为List[int],sum()和min()操作自然合法。若误传I2C对象,adc.value会报错,但类型检查在编码时就阻止了这种传参。
3.6 SPI设备配置:时钟频率与片选引脚协同管理
python复制from adafruit_typing import SPI, Pin
from typing import Optional
def configure_spi_device(
spi: SPI,
cs_pin: Pin,
baudrate: int = 1000000,
polarity: int = 0,
phase: int = 0
) -> None:
"""配置SPI设备:同时约束总线和片选引脚"""
# 类型确保spi有.configure()方法
spi.configure(baudrate=baudrate, polarity=polarity, phase=phase)
# 类型确保cs_pin是Pin,可创建DigitalInOut
cs = digitalio.DigitalInOut(cs_pin)
cs.direction = digitalio.Direction.OUTPUT
cs.value = True # 默认高电平,未选中
print(f"📡 SPI configured: {baudrate}Hz, CS on {cs_pin}")
# 正确:
# spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
# configure_spi_device(spi_bus, board.D5, baudrate=2000000)
关键设计:cs_pin: Pin要求传入物理引脚,而spi: SPI要求传入SPI总线。二者类型不同,杜绝了“用SPI总线当片选引脚”的低级错误。函数内部用digitalio.DigitalInOut(cs_pin)安全地创建片选对象,类型系统确保cs_pin是合法引脚。
3.7 多传感器数据收集:类型化批量处理避免循环崩溃
python复制from adafruit_typing import TemperatureSensor, Pin
from typing import List, Dict, Any
def collect_sensor_data(
temp_sensors: List[TemperatureSensor],
digital_pins: List[Pin]
) -> Dict[str, List[Any]]:
"""收集多传感器数据:类型确保每个元素都满足协议"""
data = {
"temperatures": [sensor.temperature for sensor in temp_sensors],
"digital_states": []
}
# 安全地为每个Pin创建DigitalInOut并读取
for pin in digital_pins:
dio = digitalio.DigitalInOut(pin)
dio.direction = digitalio.Direction.INPUT
data["digital_states"].append(dio.value)
dio.deinit() # 释放资源
return data
# 使用:
# sensors = [bme280, tmp117] # 均为TemperatureSensor
# pins = [board.D2, board.D3] # 均为Pin
# result = collect_sensor_data(sensors, pins)
类型防护:temp_sensors: List[TemperatureSensor]确保列表中每个元素都有.temperature;digital_pins: List[Pin]确保每个元素都是物理引脚,可安全传给DigitalInOut。若混入str或int,mypy在列表构建时就报错。
3.8 硬件资源管理器:类型化注册避免资源冲突
python复制from adafruit_typing import I2C, SPI, Pin
from typing import Dict, List, Tuple, TypeVar
T = TypeVar('T')
class HardwareManager:
def __init__(self):
self.used_resources: Dict[str, List[Tuple[str, T]]] = {
"i2c": [],
"spi": [],
"pins": []
}
def register_i2c(self, i2c: I2C, name: str) -> None:
"""注册I2C资源:类型确保i2c是I2C协议实例"""
self.used_resources["i2c"].append((name, i2c))
print(f"🔌 Registered I2C: {name}")
def register_pin(self, pin: Pin, name: str) -> None:
"""注册Pin资源:类型确保pin是Pin实例"""
self.used_resources["pins"].append((name, pin))
print(f"⚡ Registered Pin: {name}")
def list_resources(self) -> Dict[str, List[str]]:
"""返回资源使用摘要"""
return {
k: [n for n, _ in v]
for k, v in self.used_resources.items()
}
# 使用:
# manager = HardwareManager()
# manager.register_i2c(i2c_bus, "main_i2c")
# manager.register_pin(board.LED, "status_led")
# print(manager.list_resources())
架构意义:HardwareManager本身不操作硬件,而是用类型约束作为“资源注册表”。register_i2c(i2c: I2C)和register_pin(pin: Pin)的签名,强制你在注册时就明确资源类型,避免后续误用(如把I2C总线当Pin去设.value)。这是构建大型CircuitPython项目的基石模式。
4. 避坑:adafruit-circuitpython-typing的七个典型翻车点与抢救方案
4.1 现象:mypy报错“Cannot find implementation or library stub for module adafruit_typing”
原因:adafruit-circuitpython-typing包本身不包含运行时代码,只提供.pyi类型存根文件。mypy默认不搜索site-packages/adafruit_typing目录,且该包未在PyPI发布(仅作为CircuitPython Bundle的一部分存在)。
解决:
- 手动安装类型存根:从CircuitPython Bundle仓库下载最新
adafruit-circuitpython-typing的.pyi文件,放入项目stubs/目录; - 配置mypy:在
pyproject.toml中添加:
toml复制[tool.mypy]
plugins = ["mypy-extensions"]
[mypy.*]
follow_imports = "normal"
[mypy.*.stubs]
# 指向存根目录
- 验证:运行
mypy --show-traceback your_script.py,确认不再报找不到模块。
提示:不要用
pip install adafruit-circuitpython-typing——它不存在。存根文件必须手动获取。
4.2 现象:函数传入busio.I2C实例,mypy仍报“Argument 1 has incompatible type 'I2C'”
原因:busio.I2C类并未显式继承adafruit_typing.I2C协议,而是通过鸭子类型满足。但mypy默认要求显式继承或@runtime_checkable,否则不认为busio.I2C是I2C的实现。
解决:
- 启用鸭子类型检查:在
pyproject.toml中添加:
toml复制[tool.mypy]
# 启用协议鸭子类型检查
disallow_untyped_defs = true
disallow_incomplete_defs = true
# 关键:允许协议匹配
check_untyped_defs = true
- 或使用
cast临时绕过(不推荐长期):
python复制from typing import cast
i2c_bus = cast(I2C, busio.I2C(board.SCL, board.SDA))
4.3 现象:from adafruit_typing import I2C后,IDE提示“I2C is not defined”
原因:VS Code的Pylance或PyCharm的Python插件未正确索引.pyi存根文件,或工作区Python解释器未指向包含存根的路径。
解决:
- VS Code:在工作区设置中添加
"python.defaultInterpreterPath"指向你的venv,并在settings.json中加入:
json复制"python.analysis.extraPaths": ["./stubs"],
"python.analysis.typeCheckingMode": "basic"
- PyCharm:
File → Settings → Project → Python Interpreter → Show All → Show Interpreter Paths → + → 添加stubs目录。
4.4 现象:DigitalInOut类型检查通过,但运行时报ValueError: Pin must be an instance of microcontroller.Pin
原因:adafruit_typing.DigitalInOut是协议,而digitalio.DigitalInOut构造函数严格要求microcontroller.Pin实例(如board.D5),但board.D5在类型层面是Pin,运行时才是microcontroller.Pin。类型系统无法校验运行时Pin的具体子类。
解决:
- 接受此限制:类型系统管不到运行时Pin的精确类型,这是CircuitPython的底层约束;
- 加固运行时检查:在函数开头添加:
python复制def configure_pin(pin: DigitalInOut, direction: digitalio.Direction) -> None:
# 运行时确认pin来自board模块
if not hasattr(pin, 'id') or not isinstance(pin.id, microcontroller.Pin):
raise TypeError("pin must be a valid microcontroller.Pin")
pin.direction = direction
4.5 现象:AnalogIn类型提示正常,但adc.value返回int,adc.reference_voltage返回float,类型推断混乱
原因:AnalogIn协议中.value和.reference_voltage的类型声明在.pyi文件中可能不一致,或mypy对属性类型的推断有偏差。
解决:
- 显式类型注解:在函数内强制指定:
python复制def read_adc_stats(adc: AnalogIn, samples: int = 10) -> Tuple[float, float]:
readings: List[int] = [adc.value for _ in range(samples)] # 显式声明list类型
average = sum(readings) / len(readings) # now average is float
return (average, float(min(readings)))
- 更新存根文件:检查Bundle仓库是否有新版
.pyi修复了此问题。
4.6 现象:PWMOutput类型下,pwm.duty_cycle = 32768通过,但硬件无反应
原因:duty_cycle属性在CircuitPython中是16位整数(0-65535),但某些MCU(如RP2040)的PWM外设要求.frequency必须在特定范围内(如1kHz-1MHz),否则忽略.duty_cycle设置。
解决:
- 类型+运行时联合校验:
python复制def set_pwm_duty_cycle(pwm: PWMOutput, duty_cycle: Union[int, float],
freq: Optional[int] = None) -> None:
if freq:
pwm.frequency = freq # 强制设置频率
if not 0 <= duty_cycle <= 100:
raise ValueError("Duty cycle must be 0-100%")
pwm.duty_cycle = int(duty_cycle * 65535 / 100)
# 验证设置生效
if pwm.duty_cycle == 0 and duty_cycle > 0:
raise RuntimeError("PWM duty_cycle not applied - check frequency setting")
4.7 现象:HardwareManager.register_i2c(i2c_bus, "name")后,i2c_bus在其他地方被意外deinit()
原因:HardwareManager只存储引用,不管理I2C对象生命周期。若外部代码调用i2c_bus.deinit(),HardwareManager中存储的引用变为悬空指针,后续.scan()会崩溃。
解决:
- 资源所有权声明:在
HardwareManager中添加deinit_all()方法,集中销毁:
python复制def deinit_all(self) -> None:
for name, i2c in self.used_resources["i2c"]:
try:
i2c.deinit()
except Exception:
pass # 忽略已销毁的
self.used_resources.clear()
- 文档约定:在类docstring中明确:“
HardwareManager不自动管理资源生命周期,请在退出前调用deinit_all()”。
5. 进阶:构建你的类型安全硬件抽象层(HAL)
5.1 为什么需要自定义HAL?标准类型不够用的三个场景
adafruit-circuitpython-typing提供了基础硬件类型,但真实项目常需更高层抽象。例如:
-
场景1:传感器组
一个节点同时接BME280(温湿度)、VEML6075(UV)、SHT31(备用温湿度),它们都提供.temperature,但BME280还提供.pressure,VEML6075提供.uv_index。标准TemperatureSensor无法表达这种“超集”关系。 -
场景2:可配置外设
同一块板子,I²C总线可能接不同设备:工厂版用BME280(0x76),教育版用HTU21D(0x40)。硬编码地址破坏可移植性。 -
场景3:故障降级
主传感器失效时,自动切换到备用传感器。这需要运行时类型检查(isinstance(sensor, BackupSensor)),而Protocol不支持isinstance。
此时,你需要基于adafruit_typing构建自己的HAL。
5.2 构建可扩展的传感器协议族
python复制from adafruit_typing import TemperatureSensor, PressureSensor, HumiditySensor
from typing import Protocol, Optional, Union
# 扩展协议:支持多传感器融合
class EnvironmentalSensor(Protocol):
@property
def temperature(self) -> float: ...
@property
def humidity(self) -> float: ...
@property
def pressure(self) -> float: ...
# 具体实现:BME280满足EnvironmentalSensor
class BME280Wrapper:
def __init__(self, i2c: I2C, address: int = 0x76):
self._bme = adafruit_bme280.Adafruit_BME280_I2C(i2c, address)
@property
def temperature(self) -> float:
return self._bme.temperature
@property
def humidity(self) -> float:
return self._bme.humidity
@property
def pressure(self) -> float:
return self._bme.pressure
# 工厂函数:根据配置返回具体传感器
def create_sensor(
i2c: I2C,
config: str = "bme280" # "bme280", "sht31", "htu21d"
) -> EnvironmentalSensor:
if config == "bme280":
return BME280Wrapper(i2c, 0x76)
elif config == "sht31":
return SHT31Wrapper(i2c, 0x44)
else:
raise ValueError(f"Unknown sensor: {config}")
# 使用:类型系统确保create_sensor返回EnvironmentalSensor
sensor = create_sensor(i2c_bus, "bme280")
print(f"Temp: {sensor.temperature}, Humidity: {sensor.humidity}")
关键点:EnvironmentalSensor是自定义Protocol,它组合了多个基础协议(TemperatureSensor等),但又不依赖具体实现。create_sensor返回类型是EnvironmentalSensor,调用方无需知道底层是BME280还是SHT31——类型安全与可扩展性兼得。
5.3 硬件配置中心:用类型约束替代魔法字符串
python复制from typing import NamedTuple, Literal
# 定义硬件配置:类型安全的枚举替代字符串
class HardwareConfig(NamedTuple):
mcu: Literal["rp2040", "esp32s3", "nrf52840"]
i2c_bus: Literal["main", "aux"]
spi_bus: Literal["primary", "secondary"]
adc_channel: int
# 预定义配置
FACTORY_CONFIG = HardwareConfig(
mcu="rp2040",
i2c_bus="main",
spi_bus="primary",
adc_channel=0
)
EDUCATION_CONFIG = HardwareConfig(
mcu="esp32s3",
i2c_bus="aux",
spi_bus="secondary",
adc_channel=4
)
def init_hardware(config: HardwareConfig) -> Dict[str, Any]:
"""根据类型化配置初始化硬件"""
resources = {}
# 类型系统确保config.mcu是合法字面量
if config.mcu == "rp2040":
resources["i2c"] = busio.I2C(board.GP1, board.GP0)
elif config.mcu == "esp32s3":
resources["i2c"] = busio.I2C(board.IO1, board.IO2)
# config.adc_channel是int,可直接用于analogio
resources["adc"] = analogio.AnalogIn(board.A0 if config.adc_channel == 0 else board.A1)
return resources
# 使用:
hw = init_hardware(FACTORY_CONFIG) # 类型检查通过
# hw = init_hardware(("wrong", "main", "primary", 0)) # mypy报错:tuple size mismatch
优势:Literal类型让配置选项在编译期就受控,避免config["mcu"] == "rp2040"这种易拼错的字符串比较。NamedTuple提供不可变性和字段名提示。
5.4 故障注入测试:用Mock类型验证HAL健壮性
python复制from unittest.mock import Mock
from adafruit_typing import I2C, TemperatureSensor
# 创建Mock I2C,满足I2C协议
class MockI2C:
def __init__(self, devices: List[int] = None):
self._devices = devices or [0x76]
def scan(self) -> List[int]:
return self._devices.copy()
@property
def frequency(self) -> int:
return 100000
@frequency.setter
def frequency(self, value: int) -> None:
pass
# Mock温度传感器
class MockTemperatureSensor:
def __init__(self, temp: float = 25.0):
self._temp = temp
@property
def temperature(self) -> float:
return self._temp
# 测试HAL在设备缺失时的行为
def test_hal_with_missing_device():
# 模拟I2C总线上没有设备
mock_i2c = MockI2C(devices=[]) # 空列表
# HAL函数应优雅处理
try:
init_i2c_device(mock_i2c, 0x76) # 应抛出ValueError
assert False, "Expected ValueError for missing device"
except ValueError as e:
assert "not found" in str(e)
# 运行测试
test_hal_with_missing_device()
实践价值:用MockI2C和MockTemperatureSensor替代真实硬件,可在PC上用pytest快速验证HAL逻辑。类型系统确保Mock对象满足协议,测试代码与生产代码共享同一类型契约。
5.5 生产部署 checklist:确保类型安全落地的七件事
| 事项 | 操作 | 验证方式 |
|---|---|---|
| 1. 存根文件到位 | 将adafruit-circuitpython-typing.pyi放入stubs/目录 |
ls stubs/adafruit_typing.pyi |
| 2. mypy配置正确 | pyproject.toml中启用check_untyped_defs |
mypy --show-config | grep check_untyped_defs |
| 3. IDE索引完成 | VS Code重启或PyCharm重新索引 | 在.py文件中输入from adafruit_typing import ,看是否出现补全 |
| 4. CI集成 | GitHub Actions中添加mypy . --show-traceback |
PR提交后CI检查是否通过 |
| 5. 团队规范 | 文档规定“所有硬件参数必须标注adafruit_typing类型” | 代码审查时检查函数签名 |
| 6. 错误处理统一 | 所有硬件函数以raise ValueError处理设备异常 |
`grep -r "raise.* |
