4提供数据库存储组件和类定义逻辑电路的统一访问接口
7from typing
import Dict, Any, Optional, Union, List
8from abc
import ABC, abstractmethod
12from .component_db
import ComponentDatabase, ComponentSpec
13from .logic_circuits
import (
14 FlipFlop, Counter, ProcessorFSM, StateMachine,
15 SequentialLogic, Signal, LogicState
19 """Custom JSON encoder for component objects"""
22 if isinstance(obj, LogicState):
25 elif isinstance(obj, Enum):
28 elif hasattr(obj,
'__dict__'):
38 LOGIC_CLASS =
"logic_class"
47 MIXED_SIGNAL =
"mixed_signal"
53 def __init__(self, name: str, category: ComponentCategory):
76 def connect(self, pin: str, target, target_pin=
None):
83 def __init__(self, component_spec: ComponentSpec, db: ComponentDatabase):
84 super().
__init__(component_spec.name, ComponentCategory.CUSTOM)
96 self.
spec.parameters[name] = value
104 "electrical_params": self.
spec.electrical_params,
105 "physical_params": self.
spec.physical_params,
106 "description": self.
spec.description
109 def connect(self, pin: str, target, target_pin=
None):
110 if isinstance(target, str):
111 self.
connections[pin] = {
"target": target,
"target_pin": target_pin}
113 self.
connections[pin] = {
"target": target.name,
"target_pin": target_pin}
119 super().
__init__(logic_circuit.name, ComponentCategory.DIGITAL)
125 if hasattr(logic_circuit,
'width'):
126 self.
parameters[
'width'] = getattr(logic_circuit,
'width')
127 if hasattr(logic_circuit,
'ff_type'):
128 self.
parameters[
'flip_flop_type'] = getattr(logic_circuit,
'ff_type')
129 if hasattr(logic_circuit,
'count_up'):
130 self.
parameters[
'count_up'] = getattr(logic_circuit,
'count_up')
145 elif name ==
'count_up' and hasattr(self.
logic_circuit,
'count_up'):
154 "description": f
"{self.logic_circuit.__class__.__name__} 逻辑电路"
167 def connect(self, pin: str, target, target_pin=
None):
168 if isinstance(target, str):
169 self.
connections[pin] = {
"target": target,
"target_pin": target_pin}
171 self.
connections[pin] = {
"target": target.name,
"target_pin": target_pin}
173 def set_input(self, input_name: str, value: LogicState):
182 return LogicState.UNKNOWN
198 def create_component(self, component_name: str, component_type: str =
None, **kwargs) -> ComponentInterface:
203 spec = self.
db.get_component(component_name)
216 component_id = self.
db.create_custom_component(component_name, **kwargs)
217 spec = self.
db.get_component(component_id)
221 raise ValueError(f
"Failed to create component {component_name}")
225 circuit_type = circuit_type.lower()
227 if circuit_type ==
"flipflop":
228 ff_type = kwargs.get(
"flip_flop_type",
"D")
230 elif circuit_type ==
"counter":
231 width = kwargs.get(
"width", 8)
232 count_up = kwargs.get(
"count_up",
True)
233 return Counter(name, width, count_up)
234 elif circuit_type ==
"statemachine":
236 elif circuit_type ==
"processorfsm":
248 """组件管理器 - 提供统一的组件管理接口"""
250 def __init__(self, db_path: str =
"components.db"):
256 def create_component(self, name: str, component_type: str =
None, **kwargs) -> ComponentInterface:
271 connections: List[Dict[str, Any]] =
None) -> Dict[str, Any]:
273 if connections
is None:
277 "components": {comp.name: comp
for comp
in components},
278 "connections": connections,
279 "type": ComponentType.MODULE
293 if source_comp
and target_comp:
294 source_comp.connect(source_pin, target_comp, target_pin)
298 for _
in range(steps):
300 if isinstance(component, LogicComponent):
301 component.simulate_step()
306 "components": {name: comp.get_info()
for name, comp
in self.
components.items()},
308 "name": module[
"name"],
309 "component_count": len(module[
"components"]),
310 "connection_count": len(module[
"connections"])
311 }
for name, module
in self.
modules.items()},
312 "database_stats": self.
db.get_component_library()
318 "components": {name: comp.get_info()
for name, comp
in self.
components.items()},
320 "connections": {name: comp.connections
for name, comp
in self.
components.items()}
323 with open(filename,
'w', encoding=
'utf-8')
as f:
324 json.dump(design, f, indent=2, ensure_ascii=
False, cls=ComponentJSONEncoder)
335def create_resistor(name: str, resistance: float, tolerance: float = 0.05) -> ComponentInterface:
338 return manager.create_component(
340 parameters={
"resistance": resistance,
"tolerance": tolerance},
341 electrical_params={
"max_voltage": 50.0,
"power_rating": 0.25},
342 description=f
"{resistance}Ω 电阻器"
345def create_capacitor(name: str, capacitance: float, voltage_rating: float = 50.0) -> ComponentInterface:
348 return manager.create_component(
350 parameters={
"capacitance": capacitance},
351 electrical_params={
"voltage_rating": voltage_rating},
352 description=f
"{capacitance}F 电容器"
358 return manager.create_component(name,
"flipflop", flip_flop_type=ff_type)
360def create_counter(name: str, width: int = 8, count_up: bool =
True) -> ComponentInterface:
363 return manager.create_component(name,
"counter", width=width, count_up=count_up)
_create_logic_circuit(self, str name, str circuit_type, **kwargs)
__init__(self, ComponentDatabase db)
register_custom_type(self, str type_name, circuit_class)
ComponentInterface create_component(self, str component_name, str component_type=None, **kwargs)
Dict[str, Any] get_info(self)
set_parameter(self, str name, Any value)
Dict[str, Any] get_parameters(self)
connect(self, str pin, target, target_pin=None)
__init__(self, str name, ComponentCategory category)
ComponentInterface create_component(self, str name, str component_type=None, **kwargs)
__init__(self, str db_path="components.db")
Optional[ComponentInterface] get_component(self, str name)
Dict[str, Any] create_module(self, str name, List[ComponentInterface] components, List[Dict[str, Any]] connections=None)
export_design(self, str filename)
simulate_system(self, int steps=1)
List[str] list_components(self)
connect_components(self, str source, str source_pin, str target, str target_pin)
Optional[Dict[str, Any]] get_module(self, str name)
__init__(self, ComponentSpec component_spec, ComponentDatabase db)
connect(self, str pin, target, target_pin=None)
set_parameter(self, str name, Any value)
Dict[str, Any] get_parameters(self)
Dict[str, Any] get_info(self)
connect(self, str pin, target, target_pin=None)
__init__(self, logic_circuit)
set_input(self, str input_name, LogicState value)
Dict[str, Any] get_info(self)
set_parameter(self, str name, Any value)
LogicState get_output(self, str output_name)
Dict[str, Any] get_parameters(self)
ComponentInterface create_counter(str name, int width=8, bool count_up=True)
ComponentInterface create_capacitor(str name, float capacitance, float voltage_rating=50.0)
ComponentInterface create_flipflop(str name, str ff_type="D")
ComponentInterface create_resistor(str name, float resistance, float tolerance=0.05)
ComponentManager create_component_manager(str db_path="components.db")
SystemInfo get_system_info()