Welcome to hwtLib’s generated documentation!¶
This documentation is automatically generated from source code on every push into master which pass testing. hwtLib is package of hardware components (like vhld/verilog library) for HWToolkit (hwt python3 package) it also contains commonly used helpers and types like uint64_t, UDP header etc. Library is structuralized mostly by main interface. Note that many compoments are parametrizable and do work with multiple interfaces.
The compoment is a class which inherits from Unit class. Interfaces are added in _declr() method and parameters in _config() method of unit class. For component there is usually the schematic, which can be opened from link under the name of the component in this documentation.
hwtLib package¶
Subpackages¶
hwtLib.abstract package¶
A package of abstract components (components which needs to have some methods implemented before use) and other utilities.
Subpackages¶
hwtLib.abstract.frame_utils package¶
- hwtLib.abstract.frame_utils.join.fsm.input_B_dst_to_fsm(word_bytes: int, input_cnt: int, input_B_dst: List[List[Set[Tuple[Tuple[int, int], int, int, int]]]], can_be_zero_len_frame: List[bool])[source]¶
- Parameters
word_bytes – number of bytes in output word
input_cnt – number of input streams
input_B_dst – list with mapping of input bytes to a output bytes in each state
Format of input_B_dst is: List for each input in this list there are lists for each input byte in this list there are sets of byte destinations for each input byte byte destination is a tuple: state label, input index, time index, output byte index, input last flag
- Note
input_B_dst is produced by
hwtLib.amba.axis_comp.frame_utils.join.FrameJoinUtils.resolve_input_bytes_destinations()
- class hwtLib.abstract.frame_utils.join.input_reg_val.InputRegInputVal(parent_state_trans: StateTransItem)[source]¶
Bases:
object
Container of values for FrameJoin input register
- Variables
~.parent – the StateTransItem instance which is owning this object
~.keep – list of keep bits
~.relict – flag for word which was partially consumed
~.last – flag for end of frame
- __init__(parent_state_trans: StateTransItem)[source]¶
- class hwtLib.abstract.frame_utils.join.state_trans_info.StateTransInfo(label, word_bytes, input_cnt)[source]¶
Bases:
object
- Variables
~.label – tuple(frame id, word id)
~.outputs – list of tuples (input index, input time, input byte index)
~.last_per_input – last flags for each input if last=1 the the input word is end of the actual frame (None = don’t care value)
- __hash__ = None¶
- get_next_substate(sub_states: Dict[Tuple[int, int], StateTransInfo]) Optional[StateTransInfo] [source]¶
- class hwtLib.abstract.frame_utils.join.state_trans_item.StateTransItem(parent_table: StateTransTable, st_i: int, state_next_i: int, out_last: int)[source]¶
Bases:
object
- Variables
state – state label
input – specifies the input to a state transition
input_keep_mask – mask which will be applied to keep signal on input to the register
input_rd – ready for a input channel (if 1 the input stream will be shifted in)
output_keep – output keep values
out_byte_mux_sel – list of
- Note
input_keep_mask[0][0] = [1, 0] means reg0.in.keep = reg0.out.keep & 0b01
- __init__(parent_table: StateTransTable, st_i: int, state_next_i: int, out_last: int)[source]¶
- inputs_exactly_different(other: StateTransItem) bool [source]¶
- class hwtLib.abstract.frame_utils.alignment_utils.FrameAlignmentUtils(word_bytes: int, out_offset=0)[source]¶
Bases:
object
- Variables
~.word_bytes – number of bytes in 1 output word
- _resolve_input_bytes_destinations(frames, input_cnt)[source]¶
- Parameters
frames – list of all possible frame formats generated from streams_to_all_possible_frame_formats
input_cnt – number of input streams
- create_frame(stream_i: int, byte_cnt: int, offset_out: int, offset_in: int) Tuple[Tuple[ByteSrcInfo]] [source]¶
- Parameters
byte_cnt – number of bytes in this frame
offset_out – how many empty bytes should be put before data in frame
offset_in – how many bytes skip from imput stream
- get_bytes_in_frame_info(offset_out, offset_in, chunk_size, chunk_cnt, already_has_body_words)[source]¶
- get_important_byte_cnts(offset_out: int, offset_in: int, chunk_size: int, chunk_cnt_min: Union[int, float], chunk_cnt_max: Union[int, float])[source]¶
Filter chunk cnt range, let only those values which affect the number of valid bytes in first/last word of frame and presence of words in body frame
- join_streams(stream_data: Tuple[Tuple[Tuple[ByteSrcInfo, ...], ...], ...], offset)[source]¶
Create output frame with specified offset from input stream
- Parameters
stream_data – list of data for each stream input (stream data is list of data words, data word is a tuple of ByteSrcInfo)
offset – offset of output stream
- hwtLib.abstract.frame_utils.alignment_utils.count_not_none(items: List[Optional[ByteSrcInfo]])[source]¶
- hwtLib.abstract.frame_utils.alignment_utils.freeze_frame(f: List[List[ByteSrcInfo]]) Tuple[Tuple[ByteSrcInfo, ...], ...] [source]¶
- class hwtLib.abstract.frame_utils.byte_src_info.ByteSrcInfo(stream_i: int, word_i: int, byte_i: int, is_from_last_input_word: bool)[source]¶
Bases:
object
Container for informations about byte in stream data
- Variables
~.stream_i – index of stream
~.word_i – index of word in frame
~.byte_i – index of byte in word
~.is_from_last_input_word – true if this byte comes from last word in input frame
Submodules¶
hwtLib.abstract.addressStepTranslation module¶
- class hwtLib.abstract.addressStepTranslation.AddressStepTranslation(src_addr_step: int = 8, dst_addr_step: int = 8)[source]¶
Bases:
object
- Variables
align_bits – number of bits on source/destination address which are addressing in a single word or other address
src_addr_step – how many bits is addressing one unit of src_addr_sig
dst_addr_step – how many bits is addressing one unit of dst_addr_sig
hwtLib.abstract.busBridge module¶
hwtLib.abstract.busEndpoint module¶
- class hwtLib.abstract.busEndpoint.BusEndpoint(structTemplate, intfCls=None, shouldEnterFn=None)[source]¶
Bases:
Unit
Abstract unit
Delegate request from bus to fields of structure (fields are represented by various interfaces) write has higher priority
- Note
implementation is usually address decoder
- __init__(structTemplate, intfCls=None, shouldEnterFn=None)[source]¶
- Parameters
structTemplate – instance of HStruct which describes address space of this endpoint
intfCls – class of bus interface which should be used
shouldEnterFn – function(root_t, structFieldPath) return (shouldEnter, shouldUse) where shouldEnter is flag that means iterator over this interface should look inside of this actual object and shouldUse flag means that this field should be used (to create interface)
- static _defaultShouldEnterFn(root: HdlType, field_path: Tuple[Union[str, int]])[source]¶
Default method which resolves how the parts of input data type should be represented on interface level.
- _getAddrStep() int [source]¶
- Returns
how many bits does 1 address unit addresses, (e.g. AXI -> 8b, index to uint32_t[N] -> 32)
- _getWordAddrStep() int [source]¶
- Returns
how many address units is one word on bus (e.g. 32b AXI -> 4)
- _mkFieldInterface(structIntf: StructIntf, field: HStructField)[source]¶
Instantiate field interface for fields in structure template of this endpoint
- Returns
interface for specified field
- connectByInterfaceMap(interfaceMap: IntfMap)[source]¶
Connect “decoded” struct interface to interfaces specified in interface map
- connect_directly_mapped_read(ar_addr: RtlSignal, r_data: RtlSignal, default_r_data_drive)[source]¶
Connect the RegCntrl.din interfaces to a bus
- connect_directly_mapped_write(aw_addr: RtlSignal, w_data: RtlSignal, en: RtlSignal)[source]¶
Connect the RegCntrl.dout interfaces to a bus
- classmethod fromInterfaceMap(interfaceMap)[source]¶
Generate converter by struct data type specified by interface map
- Parameters
interfaceMap –
hwt.interfaces.intf_map.HTypeFromIntfMap()
- propagateAddr(src_addr_sig: RtlSignal, src_addr_step: int, dst_addr_sig: RtlSignal, dst_addr_step: int, transTmpl: TransTmpl)[source]¶
- Parameters
src_addr_sig – input signal with address
src_addr_step – how many bits is addressing one unit of src_addr_sig
dst_addr_sig – output signal for address
dst_addr_step – how many bits is addressing one unit of dst_addr_sig
transTmpl – TransTmpl which has meta-informations about this address space transition
hwtLib.abstract.busInterconnect module¶
- class hwtLib.abstract.busInterconnect.AUTO_ADDR[source]¶
Bases:
object
constant which means that address should be picked automatically
- class hwtLib.abstract.busInterconnect.BusInterconnect(hdl_name_override: Optional[str] = None)[source]¶
Bases:
Unit
Abstract class of bus interconnects
- Variables
~.m – HObjList of master interfaces
~.s – HObjList of slave interfaces
- class hwtLib.abstract.busInterconnect.BusInterconnectUtils[source]¶
Bases:
object
- classmethod _extract_separable_group(mi: int, seen_m: Set[int], masters_connected_to: List[Set[int]], slaves_connected_to: List[Set[int]])[source]¶
Transitive enclosure of master/stalave ports on connected relation (Extract a group of all ports which are somehow connected to each other)
hwtLib.abstract.busStaticRemap module¶
- class hwtLib.abstract.busStaticRemap.BusStaticRemap(hdl_name_override: Optional[str] = None)[source]¶
Bases:
Unit
Abstract class for component which remaps memory regions on bus interfaces
- Variables
~.MEM_MAP – list of tuples (addr_from, size, addr_to) for each memory region on second interface
~.m – slave interface of first interface class where master should be connected
~.s – slave interface of second interface class where master slave be connected
hwtLib.abstract.componentBuilder module¶
- class hwtLib.abstract.componentBuilder.AbstractComponentBuilder(parent: Unit, srcInterface: Union[Interface, HObjList], name: Optional[str] = None, master_to_slave: bool = True)[source]¶
Bases:
object
Helper class which simplifies instantiation of commonly used components with configuration based on input/output interface
- Variables
~.compId – used for sequential number of components
~.lastComp – last builded component
~.end – last interface of data-path
- Attention
input port is taken from self.end
- __init__(parent: Unit, srcInterface: Union[Interface, HObjList], name: Optional[str] = None, master_to_slave: bool = True)[source]¶
- Parameters
parent – unit in which will be all units created by this builder instantiated
name – prefix for all instantiated units
srcInterface – start of data-path
master_to_slave – if True the circuit is build in natural direction (master to slave, input to output) othervise it is build in reverse direction
hwtLib.abstract.debug_bus_monitor module¶
- class hwtLib.abstract.debug_bus_monitor.DebugBusMonitor(bus_cls, bus_endpoint_cls)[source]¶
Bases:
Unit
This component is similar to ILA/ChipScope/SignalTAP but it is not connected to internal JTAG, but to a specified interface. This component generates an address decoder and connect all specified interfaces to a service bus. It also stores the names and bit widths of original interfaces in a ROM in order to display them later in test application. This component also supports for snapshots of values by a generic trigger method, transaction counters etc.
- Note
addressspace size depends on how much data is actually monitored. But it has fixed structure.
Example of meta_memory JSON format:
- build_meta_memory(monitored_data: List[DebugBusMonitorDataRecord])[source]¶
- build_meta_memory_json(monitored_data: List[DebugBusMonitorDataRecord], data_ids: Dict[DebugBusMonitorDataRecord, int], offset: int)[source]¶
- register(intf: Interface, name: Optional[str] = None, cdc: bool = False, trigger: Optional[RtlSignal] = None, add_reg: bool = False)[source]¶
- Parameters
intf – an interface to monitor
name – name override
cdc – if True instantiate Clock domain crossing to synchronize input data to clock domain of this component
trigger – an optional signal which triggers the snapshot of this interface
add_reg – if True an register is added between input and bus interface
- Note
if cdc is set to True the trigger has to be synchonezed to a clock clock domain of intf
- class hwtLib.abstract.debug_bus_monitor.DebugBusMonitorDataRecord(intf: Interface, name: str, cdc: bool, trigger: RtlSignal, add_reg: bool)[source]¶
Bases:
object
- add_children(c: DebugBusMonitorDataRecord)[source]¶
- add_link(dst: DebugBusMonitorDataRecord)[source]¶
hwtLib.abstract.discoverAddressSpace module¶
- class hwtLib.abstract.discoverAddressSpace.AddressSpaceProbe(topIntf, getMainSigFn, offset=0)[source]¶
Bases:
object
An object which can be used to discover an address space of an interface. Discovery is made by walking on address signal.
hwtLib.abstract.hwExceptionCtx module¶
- class hwtLib.abstract.hwExceptionCtx.ExceptionHandleInterface(exception: InHwError, masterDir=DIRECTION.OUT, loadConfig=True)[source]¶
Bases:
HandshakeSync
- __init__(exception: InHwError, masterDir=DIRECTION.OUT, loadConfig=True)[source]¶
This constructor is called when constructing new interface, it is usually done manually while creating
hwt.synthesizer.unit.Unit
or automatically while extracting interfaces from UnitWithSoure- Parameters
masterDir – direction which this interface should have for master
multiplyedBy – this can be instance of integer or Param, this mean the interface is array of the interfaces where multiplyedBy is the size
loadConfig – do load config in __init__
- class hwtLib.abstract.hwExceptionCtx.HwExceptionCtx(parent: Unit, name='raise')[source]¶
Bases:
object
An object which handles hardware exceptions.
- Attention
exception handling requires a clock and reset signal to be present on parent
hwt.synthesizer.unit.Unit
instance.
- _Unit_makePublicIntfPrivateInImpl(intf: ExceptionHandleInterface)[source]¶
- _Unit_registerPublicIntfInImpl(intf: ExceptionHandleInterface, name: str)[source]¶
- hw_catch(exception_cls: Optional[Union[Type[InHwError], Tuple[Type[InHwError], ...]]] = None) List[Tuple[InHwError, ExceptionHandleInterface]] [source]¶
Catch all uncatched exceptions by exception class.
- Parameters
exception_cls – An class on exceptions which should be catched (An exception is catched if its class is a subclass of exception_cls).
- Note
Catching exception means getting IO for exception handling in this context. You need to drive all interfaces and possibly re-raise for those which should not be catched.
- Returns
List of tuples (exception, interface) for every uncatched exception in current scope (includes children). (Due to parallel nature of hardware it is a list and exceptions may be raised simulately.)
- hw_raise(exception: InHwError, pending_flag: Optional[RtlSignalBase] = None, raising_flag: Optional[RtlSignalBase] = None)[source]¶
Construct a logic to raise an exception in generated hardware. This creates a flag and IO for exception handling status.
- Parameters
pending_flag – An optional flag which should be set to 1 if exception was raised in some previous clock cycle an it has not beed catched yet.
raising_flag – An optional flag which should be set to 1 if exception exception is beeing raised in this clock cycle.
- Attention
The arguments specified in the exception has to remain stable until the excetion is handled.
- Returns
An expression which triggers the exception handling.
- propagate()[source]¶
Propagate uncatched exceptions from this
hwt.synthesizer.unit.Unit
instance and its children to IO of thishwt.synthesizer.unit.Unit
instance.- Note
The exception is considered uncached if its rd signal is not driven.
hwtLib.abstract.monitorIntf module¶
- class hwtLib.abstract.monitorIntf.MonitorIntf(template_interface)[source]¶
Bases:
Interface
Interfaces same as template interface, but with all signals as an input
- __init__(template_interface)[source]¶
This constructor is called when constructing new interface, it is usually done manually while creating
hwt.synthesizer.unit.Unit
or automatically while extracting interfaces from UnitWithSoure- Parameters
masterDir – direction which this interface should have for master
multiplyedBy – this can be instance of integer or Param, this mean the interface is array of the interfaces where multiplyedBy is the size
loadConfig – do load config in __init__
- class hwtLib.abstract.monitorIntf.MonitorIntfReg(intfCls: Type[MonitorIntf])[source]¶
Bases:
Unit
- __init__(intfCls: Type[MonitorIntf])[source]¶
- class hwtLib.abstract.monitorIntf.MonitorIntfVldSynced(template_interface)[source]¶
Bases:
VldSynced
- __init__(template_interface)[source]¶
This constructor is called when constructing new interface, it is usually done manually while creating
hwt.synthesizer.unit.Unit
or automatically while extracting interfaces from UnitWithSoure- Parameters
masterDir – direction which this interface should have for master
multiplyedBy – this can be instance of integer or Param, this mean the interface is array of the interfaces where multiplyedBy is the size
loadConfig – do load config in __init__
- class hwtLib.abstract.monitorIntf.MonitorIntfVldSyncedCdc(template_interface)[source]¶
Bases:
VldSyncedCdc
- hwtLib.abstract.monitorIntf._connect_MonitorIntf(src: MonitorIntf, dst)[source]¶
- hwtLib.abstract.monitorIntf._connect_to_MonitorIntf(src, dst: MonitorIntf)[source]¶
- hwtLib.abstract.monitorIntf.connect_MonitorIntf(src: MonitorIntf, dst)[source]¶
Connect signal by signal and ignore the directions of struct interface (check only direction of low level signals)
- hwtLib.abstract.monitorIntf.connect_to_MonitorIntf(src, dst: MonitorIntf)[source]¶
Connect signal by signal and ignore the directions of struct interface (check only direction of low level signals)
hwtLib.abstract.sim_ram module¶
- exception hwtLib.abstract.sim_ram.AllocationError[source]¶
Bases:
Exception
Exception which says that requested allocation can not be performed
- class hwtLib.abstract.sim_ram.SimRam(cellSize, parent=None)[source]¶
Bases:
object
Dense memory for simulation purposes with data pump interfaces
- Variables
~.data – memory dict
- __init__(cellSize, parent=None)[source]¶
- Parameters
cellWidth – width of items in memory
clk – clk signal for synchronization
parent – parent instance of SimRam (memory will be shared with this instance)
- _getArray(offset, transTmpl)[source]¶
- Parameters
offset – global offset of this transTmpl (and struct)
transTmpl – instance of TransTmpl which specifies items in array
- _getStruct(offset, transTmpl)[source]¶
- Parameters
offset – global offset of this transTmpl (and struct)
transTmpl – instance of TransTmpl which specifies items in struct
- calloc(num, size, keepOut=None, initValues=None) int [source]¶
Allocates a block of memory for an array of num elements, each of them size bytes long, and initializes all its bits to zero.
- Parameters
num – Number of elements to allocate.
size – Size of each element.
keepOut – optional memory spacing between this memory region and lastly allocated (number of bit between last allocated segment to avoid)
initValues – iterable of word values to init memory with
- Returns
address (byte step) of allocated memory
- getBits(start, end, sign)[source]¶
Gets value of bits between selected range from memory
- Parameters
start – bit address of start of bit of bits
end – bit address of first bit behind bits
- Returns
instance of BitsVal (derived from SimBits type) which contains copy of selected bits
- hwtLib.abstract.sim_ram.reshapedInitItems(actualCellSize, requestedCellSize, values)[source]¶
Convert array item size and items cnt while size of array remains unchanged
- Parameters
actualCellSize – actual size of item in array
requestedCellSize – requested size of item in array
values – input array
- Returns
generator of new items of specified characteristic
hwtLib.abstract.streamBuilder module¶
- class hwtLib.abstract.streamBuilder.AbstractStreamBuilder(parent: Unit, srcInterface: Union[Interface, HObjList], name: Optional[str] = None, master_to_slave: bool = True)[source]¶
Bases:
AbstractComponentBuilder
- Note
see
AbstractComponentBuilder
- Attention
this is just abstract class unit classes has to be specified in concrete implementation
- Variables
~.FifoCls – FIFO unit class
~.FifoAsyncCls – asynchronous FIFO (FIFO with separate clock per port) unit class
~.JoinSelectCls – select order based join unit class
~.JoinFairCls – round robin based join unit class
~.JoinPrioritizedCls – priority based join unit class
~.RegCls – register unit class
~.RegCdcCls – Clock domain crossing register unit class
~.ResizerCls – resizer unit class (used to change data width of an interface)
~.SplitCopyCls – copy based split unit class
~.SplitSelectCls – select order based split unit class (demultiplexer)
~.SplitFairCls – round robin based split unit class
~.SplitPrioritizedCls – priority based split unit class
- FifoAsyncCls = NotImplemented¶
- FifoCls = NotImplemented¶
- JoinFairCls = NotImplemented¶
- JoinPrioritizedCls = NotImplemented¶
- JoinSelectCls = NotImplemented¶
- RegCls = NotImplemented¶
- ResizerCls = NotImplemented¶
- SplitCopyCls = NotImplemented¶
- SplitFairCls = NotImplemented¶
- SplitPrioritizedCls = NotImplemented¶
- SplitSelectCls = NotImplemented¶
- _genericInstance(unit_cls, name, set_params=<function AbstractStreamBuilder.<lambda>>, update_params=True, propagate_clk_rst=True)[source]¶
Instantiate generic component and connect basics
- Parameters
unit_cls – class of unit which is being created
name – name for unit_cls instance
set_params – function which updates parameters as is required (parameters are already shared with self.end interface)
- classmethod _join(joinCls, parent, srcInterfaces, name, configAs, extraConfigFn)[source]¶
Create builder from many interfaces by joining them together
- Parameters
joinCls – join component class which should be used
parent – unit where builder should place components
srcInterfacecs – sequence of interfaces which should be joined together (lower index = higher priority)
configureAs – interface or another object which configuration should be applied
extraConfigFn – function which is applied on join unit in configuration phase (can be None)
- buff(items: int = 1, latency: Union[None, int, Tuple[int, int]] = None, delay: Optional[int] = None, init_data: tuple = ())[source]¶
Use registers and FIFOs to create buffer of specified parameters :note: if items <= latency registers are used else FIFO is used
- Parameters
items – number of items in buffer
latency – latency of buffer (number of clk ticks required to get data from input to input)
delay – delay of buffer (number of clk ticks required to get data to buffer)
init_data – a reset value of buffer (data is transfered after reset) if items=1 and interface has just data:uint8_t signal the init_data will be in format ((0,),)
- Note
delay can be used as synchronization method or to solve timing related problems because it will split valid signal path
- Note
if latency or delay is None the most optimal value is used
- buff_cdc(clk, rst, items=1)[source]¶
Instantiate a CDC (Clock Domain Crossing) buffer or AsyncFifo on selected interface
- Note
if items==1 CDC clock synchronization register is used if items>1 asynchronous FIFO is used
- classmethod join_fair(parent, srcInterfaces, name=None, configAs=None, exportSelected=False)[source]¶
create builder from fairly joined interfaces (round robin for input select)
- Parameters
exportSelected – if True join component will have handshaked interface with index of selected input
- Note
other parameters same as in .AbstractStreamBuilder._join
- classmethod join_prioritized(parent, srcInterfaces, name=None, configAs=None, extraConfigFn=None)[source]¶
create builder from fairly joined interfaces (round robin for input select)
- Note
other parameters same as in .AbstractStreamBuilder._join
- split_copy(noOfOutputs)[source]¶
Clone input data to all outputs
- Parameters
noOfOutputs – number of output interfaces of the split
- split_copy_to(*outputs)[source]¶
Same like split_copy, but outputs are automatically connected
- Parameters
outputs – ports on which should be outputs of split component connected to
- split_fair(noOfOutputs, exportSelected=False)[source]¶
Create a round robin selector with number of outputs specified by noOfOutputs
- Parameters
noOfOutputs – number of outputs of multiplexer
exportSelected – if is True split component will have interface “selectedOneHot” of type VldSynced wich will have one hot index of selected item
- split_fair_to(*outputs, exportSelected=False)[source]¶
Same like split_fair, but outputs are automatically connected
- Parameters
outputs – ports on which should be outputs of split component connected to
exportSelected – if is True split component will have interface “selectedOneHot” of type VldSynced which will have one hot index of selected item
- split_prioritized(noOfOutputs)[source]¶
data from input is send to output which is ready and has highest priority from all ready outputs
- Parameters
noOfOutputs – number of output interfaces of the fork
- split_prioritized_to(*outputs)[source]¶
Same like split_prioritized, but outputs are automatically connected
- Parameters
outputs – ports on which should be outputs of split component connected to
- split_select(outputSelSignalOrSequence, noOfOutputs)[source]¶
Create a demultiplexer with number of outputs specified by noOfOutputs
- Parameters
noOfOutputs – number of outputs of multiplexer
outputSelSignalOrSequence – handshaked interface (onehot encoded) to control selected output or sequence of output indexes which should be used (will be repeated)
hwtLib.abstract.template_configured module¶
- hwtLib.abstract.template_configured.HdlType_separate(t: HdlType, do_separate_query: Callable[[HdlType], bool]) Generator[Tuple[bool, HdlType], None, None] [source]¶
Split HStruct type hierachy on the specified fields to multiple type definitions.
- class hwtLib.abstract.template_configured.TemplateConfigured(structT: HdlType, tmpl: Optional[TransTmpl] = None, frames: Optional[List[FrameTmpl]] = None)[source]¶
Bases:
object
Class with functions for extracting metadata from frame template/HdlType. Used for resolving of data mapping between abstract type and physical interface.
- __init__(structT: HdlType, tmpl: Optional[TransTmpl] = None, frames: Optional[List[FrameTmpl]] = None)[source]¶
- Parameters
structT – instance of HStruct used as template for this frame If name is None no input port is generated and space is filled with invalid values, little-endian encoding, supported types of interfaces are: Handshaked, Signal can be also instance of FrameTmpl
tmpl – instance of TransTmpl for this structT
frames – list of FrameTmpl instances for this tmpl
- Note
if tmpl and frames are None they are resolved from structT parseTemplate
- chainFrameWords() Generator[Tuple[int, List[Union[TransPart, ChoicesOfFrameParts]], bool], None, None] [source]¶
hwtLib.cesnet package¶
https://www.cesnet.cz related components, interfaces and utilities.
Subpackages¶
hwtLib.peripheral package¶
Subpackages¶
hwtLib.peripheral.usb package¶
This package contains components, interfaces, data types and other utils related to Universal Serial Bus (USB) protocol.
The USB bus is composed of Host (the main device which controls the bus), Hub(s) (a port extender) and a Device(s). The USB protocol stack (v3.2) is composed of multiple layers as depicted in:

Functional Layer:
This layer generates requests which are converted into transactions containing different packets. It also manages end to end data flow between host and device.
Protocol Layer:
Packets originates at transmit part of protocol layer and terminates at receive part of protocol layer. It has various functions which include following.
Ensure end to end reliability of packets.
Ensure effective management of power.
Ensure effective use of Bandwidth.
Link Layer:
This layer manages port to port flow of data between USB host and device. Link layer commands ensure link level data integrity, flow control and power management. This layer handles packet acknowledgement and takes care of error recovery. The Link Layer also handles Header Packet Framing. Its functions are similar to MAC layer of OSI model.
Physical Layer:
This layer offers actual physical connection between two ports. The connection uses a single differential pair (<= USB 2.0) or two differential data pairs (>= USB 3.0) (one transmit path and one receive path). The USB <=2.0 physical layer performs NRZI (Non Return to Zero Invert) encoding and bit stuffing. In the USB >=3.0 and <3.2 physical layer the transmit part of physical layer performs data scrambling, 8b10b encoding, and serialization functions. And the receive part of physical Layer performs de-serialization, 8b10b decoding, data descrambling, and receiver clock and data recovery. In USB >=3.2 it may have additional RX and TX lane.
- note
USB Documentation, Christopher D. Leary and Devrin TalenDecember 17, 2007
Bus Enumeration
Host waits for at least 100 ms to account for the insertion process.
Host resets the device. Device should now be at address 0 and the defaultcontrol pipe will be open (default state).
Host queries the device descriptor from the devices default control pipe.
The host controller assigns a unique address to the device.
Host queries all configuration descriptors from the device, then sets one.At this point, the device will begin to draw the amount of power requestedby the assigned interface.
Host queries all other remaining descriptors (interface, endpoint, etc.) andsets up any requested interrupt transfers.
USB Endpoints
In the USB specification, a device endpoint is a uniquely addressable portion of a USB device that is the source or sink of information in a communication flow between the host and device. The Ep0 has is dedicated to control and and it provides descriptors for other endpoints.
The Endpoints may support following types of transfer:
Control
Interrupt
Bulk
Isochronous

Similar projects: * https://github.com/WangXuan95/FPGA-USB-Device
- class hwtLib.peripheral.usb.descriptors.bundle.UsbDescriptorBundle(*args, **kwargs)[source]¶
Bases:
list
Container of USB descriptors.
- Variables
compiled_rom – list of bytes for descriptor rom generated from this descriptor bundle
compiled_type_to_addr_and_size – a dictionary mapping the descriptor type to list of tuples address size for a localization of the descriptor in compiled rom
- get_descr_bytes(start_descr_i: int, wLength: int) List[int] [source]¶
Start at the beginning of the descriptor on index start_descr_i and copy specified number of bytes from that location (may overlap to other descriptors as well)
- get_descriptor(descr_t, descr_i: int) Tuple[int, HValue] [source]¶
Get an index of descriptor of a specific type
- Parameters
descr_t – specific type of descriptor
descr_i – index of this descriptor of this specific type (excluding any descriptors of different type)
- get_descriptors_from_rom(descr_t: USB_DESCRIPTOR_TYPE) Tuple[int, int] [source]¶
Get the address and size of descriptor in comiled rom memory
- Parameters
i – index of the decriptor in a list of descriptors of this type to get
- Returns
tuple address, size
- get_endpoint_meta() Tuple[Tuple[Optional[UsbEndpointMeta], Optional[UsbEndpointMeta]]] [source]¶
- class hwtLib.peripheral.usb.descriptors.bundle.UsbEndpointMeta(index: int, dir_: USB_ENDPOINT_DIR, supports_setup: bool = False, supports_bulk: bool = False, supports_interrupt: bool = False, supports_isochronoust: bool = False, max_packet_size: int = 0, buffer_size: Optional[int] = None)[source]¶
Bases:
object
Information about USB endpoint extracted from
UsbDescriptorBundle
- __init__(index: int, dir_: USB_ENDPOINT_DIR, supports_setup: bool = False, supports_bulk: bool = False, supports_interrupt: bool = False, supports_isochronoust: bool = False, max_packet_size: int = 0, buffer_size: Optional[int] = None)[source]¶
This file contains a data structures used for communication and configuration of USB CDC UART device. Based on: https://www.silabs.com/documents/public/application-notes/AN758.pdf
- class hwtLib.peripheral.usb.descriptors.cdc.CHAR_FORMAT[source]¶
Bases:
object
- STOP_BIT_1 = 0¶
- STOP_BIT_1_5 = 1¶
- STOP_BIT_2 = 2¶
- class hwtLib.peripheral.usb.descriptors.cdc.CLASS_REQUEST[source]¶
Bases:
object
- GET_LINE_CODING = 33¶
- SET_CONTROL_LINE_STATE = 34¶
- SET_LINE_CODING = 32¶
- class hwtLib.peripheral.usb.descriptors.cdc.PARITY_TYPE[source]¶
Bases:
object
- EVEN = 2¶
- MARK = 3¶
- NONE = 0¶
- ODD = 1¶
- SPACE = 4¶
- class hwtLib.peripheral.usb.descriptors.cdc.USB_CDC_DESCRIPTOR_SUBTYPE[source]¶
Bases:
object
- ABSTRACT_CONTROL_MANAGEMENT = 2¶
- ATM_NETWORKING_FUNCTIONAL = 16¶
- CALL_MANAGEMENT_FUNCTIONAL = 1¶
- CAPI_CONTROL_MANAGEMENT = 14¶
- COUNTRY_SELECTION_FUNCTIONAL = 7¶
- DIRECT_LINE_MANAGEMENT = 3¶
- ETHERNET_NETWORKING_FUNCTIONAL = 15¶
- EXTENSION_UNIT_FUNCTIONAL = 12¶
- HEADER = 0¶
- MULTI_CHANNEL_MANAGEMENT = 13¶
- NETWORK_CHANNEL_TERMINAL = 10¶
- PROTOCOL_UNIT_FUNCTIONAL = 11¶
- TELEPHONE_CALL_AND_LINE_STATE_REPORTING_CAPABILITIES = 5¶
- TELEPHONE_OPERATIONAL_MODES = 8¶
- TELEPHONE_RINGER_FUNCTIONAL = 4¶
- UNION = 6¶
- USB_TERMINAL_FUNCTIONAL = 9¶
- hwtLib.peripheral.usb.descriptors.cdc.get_default_usb_cdc_vcp_descriptors(usbVer='2.0', bMaxPacketSize=64, manufacturerStr: Optional[str] = None, productStr: Optional[str] = None, deviceVer: str = '0.0') UsbDescriptorBundle [source]¶
Generates USB descriptors for USB CDC device which works as a UART (serial)
- hwtLib.peripheral.usb.descriptors.cdc.make_descriptor_functional_abstract_control_management(capability_commFeature: bool, capability_lineCodingAndSerialState: bool, capability_sendBreak: bool, capability_networkConnection: bool)[source]¶
- hwtLib.peripheral.usb.descriptors.cdc.make_descriptor_functional_call_management(supportHandlesCallManagementItself: bool, supportManagementOverDataClassInterface: bool, bDataInterface: int)[source]¶
- hwtLib.peripheral.usb.descriptors.cdc.make_descriptor_functional_union(bMasterInterface: int, bSlaveInterface: List[int])[source]¶
- hwtLib.peripheral.usb.descriptors.cdc.make_usb_line_coding_default(dwDTERate=115200, bCharFormat=0, bParityType=0, bDataBits=8)[source]¶
- class hwtLib.peripheral.usb.descriptors.hid.USB_HID_COUNTRY_CODE[source]¶
Bases:
object
- ARABIC = 1¶
- BELGIAN = 2¶
- CANADIAN_BILINGUAL = 3¶
- CANADIAN_FRENCH = 4¶
- CZECH_REPUBLIC = 5¶
- DANISH = 6¶
- FINNISH = 7¶
- FRENCH = 8¶
- GERMAN = 9¶
- GREEK = 10¶
- HEBREW = 11¶
- HUNGARY = 12¶
- INTERNATIONAL_ISO = 13¶
- ITALIAN = 14¶
- JAPAN_KATAKANA = 15¶
- KOREAN = 16¶
- LATIN_AMERICAN = 17¶
- NETHERLANDS_DUTCH = 18¶
- NORWEGIAN = 19¶
- NOT_SUPPORTED = 0¶
- PERSIAN_FARSI = 20¶
- POLAND = 21¶
- PORTUGUESE = 22¶
- RUSSIA = 23¶
- SLOVAKIA = 24¶
- SPANISH = 25¶
- SWEDISH = 26¶
- SWISS_FRENCH = 27¶
- SWISS_GERMAN = 28¶
- SWITZERLAND = 29¶
- TAIWAN = 30¶
- TURKISH_F = 35¶
- TURKISH_Q = 31¶
- UK = 32¶
- US = 33¶
- YUGOSLAVIA = 34¶
- class hwtLib.peripheral.usb.descriptors.hid.USB_HID_PROTOCOL[source]¶
Bases:
object
- KEYBOARD = 1¶
- MOUSE = 2¶
- NONE = 0¶
- class hwtLib.peripheral.usb.descriptors.hid.USB_HID_SUBLCASS[source]¶
Bases:
object
- BOOT_INTERFACE = 1¶
- NONE = 0¶
- hwtLib.peripheral.usb.descriptors.hid.make_usb_descriptor_hid(hidVer: str, bCountryCode: USB_HID_COUNTRY_CODE, bNumDescriptors: int, bDescriptorType: USB_DESCRIPTOR_TYPE, wDescriptorLength: int)[source]¶
- class hwtLib.peripheral.usb.descriptors.std.USB_DESCRIPTOR_TYPE[source]¶
Bases:
object
- CONFIGURATION = 2¶
- DEVICE = 1¶
- DEVICE_QUALIFIER = 6¶
- ENDPOINT = 5¶
- FUNCTIONAL = 36¶
- HID = 33¶
- INTERFACE = 4¶
- INTERFACE_POWER = 8¶
- OTHER_SPEED_CONFIGURATION = 7¶
- REPORT = 34¶
- STRING = 3¶
- class hwtLib.peripheral.usb.descriptors.std.USB_DEVICE_CLASS[source]¶
Bases:
object
https://www.usb.org/defined-class-codes
- APPLICATION_SPECIFIC = 254¶
- AUDIO = 1¶
- AUDIO_VIDEO_DEVICE = 16¶
- BILBOARD_DEVICE = 17¶
- CDC_CONTROL = 2¶
- CDC_DATA = 10¶
- CONTENT_SECURITY = 13¶
- DIAGNOSTIC_DEVICE = 220¶
- HID = 3¶
- IMAGE = 6¶
- MASS_STORAGE = 8¶
- MISCELLANEOUS = 239¶
- PERSONAL_HEALTHCARE = 15¶
- PRINTER = 7¶
- SMART_CARD = 11¶
- UNSPECIFIED = 0¶
- USB_HUB = 9¶
- USB_PID = 5¶
- USB_TYPE_C_BRIDGE = 18¶
- VENDOR_SPECIFIC = 255¶
- VIDEO = 14¶
- WIRELESS_CONTROLLER = 224¶
- class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_ATTRIBUTES_SYNCHRONISATION_TYPE[source]¶
Bases:
object
Note only apply to isochronous endpoints.
- ADAPTIVE = 2¶
- ASYNCHRONOUS = 1¶
- NONE = 0¶
- SYNCHRONOUS = 3¶
- class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_ATTRIBUTES_TRANSFER_TYPE[source]¶
Bases:
object
- BULK = 2¶
- CONTROL = 0¶
- INTERRUPT = 3¶
- ISOCHRONOUS = 1¶
- class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_ATTRIBUTES_USAGE_TYPE[source]¶
Bases:
object
- DATA = 0¶
- FEEDBACK = 1¶
- IMPLICIT_FEEDBACK_DATA = 2¶
- RESERVED = 3¶
- class hwtLib.peripheral.usb.descriptors.std.USB_ENDPOINT_DIR[source]¶
Bases:
object
- IN = 1¶
- OUT = 0¶
- hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_configuration(wTotalLength: int, bNumInterfaces: int, bConfigurationValue: int, iConfiguration: int, remoteWakeup: int = 0, selfPowered: int = 0, bMaxPower: int = 250)[source]¶
- hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_device(bDeviceClass: USB_DEVICE_CLASS, bDeviceSubClass=0, bDeviceProtocol=255, usbVer: USB_VER = '2.0', bMaxPacketSize=64, idVendor=4660, idProduct=22136, bcdDevice='0.1', iManufacturer=1, iProduct=2, iSerialNumber=0, bNumConfigurations=1)[source]¶
- hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_device_qualifier(bDeviceClass: USB_DEVICE_CLASS, bDeviceSubClass=0, bDeviceProtocol=255, usbVer: USB_VER = '2.0', bMaxPacketSize=64, bNumConfigurations=1)[source]¶
- hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_endpoint(bEndpointAddressDir: USB_ENDPOINT_DIR, bEndpointAddress: int, attr_transferType: USB_ENDPOINT_ATTRIBUTES_TRANSFER_TYPE, attr_synchronisationType: USB_ENDPOINT_ATTRIBUTES_SYNCHRONISATION_TYPE, attr_usageType: USB_ENDPOINT_ATTRIBUTES_USAGE_TYPE, wMaxPacketSize: int, bInterval: int)[source]¶
- hwtLib.peripheral.usb.descriptors.std.make_usb_descriptor_interface(bInterfaceNumber: int, bAlternateSetting: int, bNumEndpoints: int, bInterfaceClass: USB_DEVICE_CLASS, bInterfaceSubClass: int, bInterfaceProtocol: int, iInterface: int)[source]¶
- class hwtLib.peripheral.usb.sim.usbip.connection.USBIPConnection(server: UsbipServer, reader: StreamReader, writer: StreamWriter)[source]¶
Bases:
object
Server container of informations about USBIP client connection
- OP_COMMON = '>HIIII'¶
- OP_COMMON_SIZE = 18¶
- OP_SUBMIT = '>IiIIi8s'¶
- OP_SUBMIT_SIZE = 28¶
- __init__(server: UsbipServer, reader: StreamReader, writer: StreamWriter)[source]¶
- async handle_urb_submit(seqnum: int, dev: USBIPDevice, direction, ep)[source]¶
- async handle_urb_unlink(seqnum, dev: USBIPDevice, direction, ep)[source]¶
- classmethod make_usbip_header_basic(command: int, seqnum: int, devid: int, direction: int, ep: int)[source]¶
- pack_device_desc(dev: USBIPSimDevice, interfaces=True)[source]¶
Pack a device descriptors into bytes for stransport to client
- class hwtLib.peripheral.usb.sim.usbip.device.LIBUSB_TRANSFER_STATUS[source]¶
Bases:
object
- TRANSFER_CANCELLED = 3¶
- TRANSFER_COMPLETED = 0¶
- TRANSFER_ERROR = 1¶
- TRANSFER_NO_DEVICE = 5¶
- TRANSFER_OVERFLOW = 6¶
- TRANSFER_STALL = 4¶
- TRANSFER_TIMED_OUT = 2¶
- class hwtLib.peripheral.usb.sim.usbip.device.USBIPDevice(devid: Tuple[int, int], hnd: USBIPSimDevice)[source]¶
Bases:
object
- __init__(devid: Tuple[int, int], hnd: USBIPSimDevice)[source]¶
- class hwtLib.peripheral.usb.sim.usbip.device.USBIPOperationPromise(operation_process, sim, clk)[source]¶
Bases:
object
- class hwtLib.peripheral.usb.sim.usbip.device.USBIPPending(seqnum, device, xfer)[source]¶
Bases:
object
- class hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDevice(usb_agent, addr: int, descriptors: UsbDescriptorBundle)[source]¶
Bases:
object
- Attention
API of this component should be same as the device from library usb1 if possible because we want to just swap the device object in sim and test the real device as well
- __init__(usb_agent, addr: int, descriptors: UsbDescriptorBundle)[source]¶
- async controlRead(bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION, bRequest, wValue, wIndex, wLength)[source]¶
- async controlWrite(bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION, bRequest: int, wValue: int, wIndex: int, data)[source]¶
- Returns
The number of bytes actually sent.
- USBIPSimDeviceConfiguration(dev: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDevice, config_descr: struct usb_descriptor_configuration_t {
- USBIPSimDeviceConfiguration struct usb_descriptor_header_t {
- USBIPSimDeviceConfiguration <Bits, 8bits, unsigned> bLength
- USBIPSimDeviceConfiguration <Bits, 8bits, unsigned> bDescriptorType
- USBIPSimDeviceConfiguration } header
- USBIPSimDeviceConfiguration struct usb_descriptor_configuration_body_t {
- USBIPSimDeviceConfiguration <Bits, 16bits, unsigned> wTotalLength
- USBIPSimDeviceConfiguration <Bits, 8bits, unsigned> bNumInterfaces
- USBIPSimDeviceConfiguration <Bits, 8bits, unsigned> bConfigurationValue
- USBIPSimDeviceConfiguration <Bits, 8bits, unsigned> iConfiguration
- USBIPSimDeviceConfiguration struct usb_configuration_body_bmAttributes_t {
- USBIPSimDeviceConfiguration <Bits, 5bits> reserved0
- USBIPSimDeviceConfiguration <Bits, 1bit> remoteWakeup
- USBIPSimDeviceConfiguration <Bits, 1bit> selfPowered
- USBIPSimDeviceConfiguration <Bits, 1bit> reserved1
- USBIPSimDeviceConfiguration } bmAttributes
- USBIPSimDeviceConfiguration <Bits, 8bits, unsigned> bMaxPower
- USBIPSimDeviceConfiguration } body
- USBIPSimDeviceConfiguration})
Bases:
object
- USBIPSimDeviceConfiguration.__init__(dev: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDevice, config_descr: struct usb_descriptor_configuration_t {
- USBIPSimDeviceConfiguration.__init__ struct usb_descriptor_header_t {
- USBIPSimDeviceConfiguration.__init__ <Bits, 8bits, unsigned> bLength
- USBIPSimDeviceConfiguration.__init__ <Bits, 8bits, unsigned> bDescriptorType
- USBIPSimDeviceConfiguration.__init__ } header
- USBIPSimDeviceConfiguration.__init__ struct usb_descriptor_configuration_body_t {
- USBIPSimDeviceConfiguration.__init__ <Bits, 16bits, unsigned> wTotalLength
- USBIPSimDeviceConfiguration.__init__ <Bits, 8bits, unsigned> bNumInterfaces
- USBIPSimDeviceConfiguration.__init__ <Bits, 8bits, unsigned> bConfigurationValue
- USBIPSimDeviceConfiguration.__init__ <Bits, 8bits, unsigned> iConfiguration
- USBIPSimDeviceConfiguration.__init__ struct usb_configuration_body_bmAttributes_t {
- USBIPSimDeviceConfiguration.__init__ <Bits, 5bits> reserved0
- USBIPSimDeviceConfiguration.__init__ <Bits, 1bit> remoteWakeup
- USBIPSimDeviceConfiguration.__init__ <Bits, 1bit> selfPowered
- USBIPSimDeviceConfiguration.__init__ <Bits, 1bit> reserved1
- USBIPSimDeviceConfiguration.__init__ } bmAttributes
- USBIPSimDeviceConfiguration.__init__ <Bits, 8bits, unsigned> bMaxPower
- USBIPSimDeviceConfiguration.__init__ } body
- USBIPSimDeviceConfiguration.__init__})
- USBIPSimDeviceInterface(conf: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDeviceConfiguration, descr: struct usb_descriptor_interface_t {
- USBIPSimDeviceInterface struct usb_descriptor_header_t {
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bLength
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bDescriptorType
- USBIPSimDeviceInterface } header
- USBIPSimDeviceInterface struct usb_descriptor_interface_body_t {
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bInterfaceNumber
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bAlternateSetting
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bNumEndpoints
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bInterfaceClass
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bInterfaceSubClass
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> bInterfaceProtocol
- USBIPSimDeviceInterface <Bits, 8bits, unsigned> iInterface
- USBIPSimDeviceInterface } body
- USBIPSimDeviceInterface})
Bases:
object
- USBIPSimDeviceInterface.__init__(conf: ~hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDeviceConfiguration, descr: struct usb_descriptor_interface_t {
- USBIPSimDeviceInterface.__init__ struct usb_descriptor_header_t {
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bLength
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bDescriptorType
- USBIPSimDeviceInterface.__init__ } header
- USBIPSimDeviceInterface.__init__ struct usb_descriptor_interface_body_t {
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bInterfaceNumber
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bAlternateSetting
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bNumEndpoints
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bInterfaceClass
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bInterfaceSubClass
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> bInterfaceProtocol
- USBIPSimDeviceInterface.__init__ <Bits, 8bits, unsigned> iInterface
- USBIPSimDeviceInterface.__init__ } body
- USBIPSimDeviceInterface.__init__})
- class hwtLib.peripheral.usb.sim.usbip.device.USBIPSimDeviceInterfaceSetting(intf: USBIPSimDeviceInterface)[source]¶
Bases:
object
- class hwtLib.peripheral.usb.sim.usbip.device.USBIPTransfer(dev: USBIPSimDevice)[source]¶
Bases:
object
- __init__(dev: USBIPSimDevice)[source]¶
- setBulk(ep: int, buff_or_len: Union[int, bytes], callback: Callable[[USBIPTransfer], None])[source]¶
This server allows to connect virtual USB devices in the simulator directly to any machine which supports USBIP.
Based on https://github.com/jwise/pyusbip/blob/master/pyusbip.py https://www.kernel.org/doc/html/latest/usb/usbip_protocol.html https://forums.aws.amazon.com/thread.jspa?messageID=968176
- note
usbip is a part of linux-tools-common apt package but in /usr/bin/ is only a placeholder the /usr/lib/linux-tools-uname -r/usbipd
https://developer.ridgerun.com/wiki/index.php?title=How_to_setup_and_use_USB/IP
- note
on some machines /usr/bin/usbip does not work correctly because the version of a kernel slightly differs from version of linux tools /usr/lib/linux-tools-5.8.0-25/usbip /usr/lib/linux-tools-5.9.0-050900-generic/usbip
modprobe vhci_hcd
usbip list -r 127.0.0.1 -l
usbip attach -r 127.0.0.1 -b 0-1
usbip port -r 127.0.0.1
usbip detach -p 00
- class hwtLib.peripheral.usb.sim.usbip.server.UsbipServer(usb_ag: UtmiUsbAgent, host='127.0.0.1', port=3240, debug=False)[source]¶
Bases:
object
- __init__(usb_ag: UtmiUsbAgent, host='127.0.0.1', port=3240, debug=False)[source]¶
- install_session_recorder(session_recoder: UsbipServerSessionRecorder)[source]¶
- class hwtLib.peripheral.usb.sim.usbip.session_recorder.UsbipServerReplayer(usb_ag: UtmiUsbAgent, session_data, debug=False)[source]¶
Bases:
UsbipServer
- __init__(usb_ag: UtmiUsbAgent, session_data, debug=False)[source]¶
- class hwtLib.peripheral.usb.sim.usbip.session_recorder.UsbipServerSessionRecorder(sim: HdlSimulator)[source]¶
Bases:
object
Used to record the client-server communication in
hwtLib.peripheral.usb.sim.usbip.server.UsbipServer
for later replay.- class Reader(sim: HdlSimulator, original: StreamReader, dst: List[List[int]])[source]¶
Bases:
object
- hwtLib.peripheral.usb.sim.usbip.session_recorder.cut_off_empty_time_segments(data: List[Tuple[int, str, List[int]]], time_segments: List[Tuple[int, int]]) List[Tuple[int, str, List[int]]] [source]¶
- Note
if time segments contains some transaction the assertion error is raised
- Note
if segment (0,10) is cut off from times 0, 10, 11 it becomes 0, 1, 2
- Parameters
time_segments – list of ranges of times to cut off (the time after is shifted)
- Returns
filtered list of data from input
- hwtLib.peripheral.usb.sim.usbip.session_recorder.filter_empty_in(_data: List[Tuple[int, str, List[int]]], seqnum_to_rm: Set[int]) List[Tuple[int, str, List[int]]] [source]¶
Remove empty IN transfers from endpoints other than 0 and remove transactions by seqnum
- Parameters
_data – list of tuples time, r/w, list of bytes
seqnum_to_rm – set of seqnum to remove (all parts of the transaction with that specified seqnum are removed entirely)
cut_off_segments – list of ranges of times to cut off (the time after is shifted)
- Returns
filtered list of data from input
- class hwtLib.peripheral.usb.sim.agent_base.UsbAgent(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]¶
Bases:
object
- __init__(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]¶
- deparse_packet(p)[source]¶
Called to convert the packet from types supported by this class before putting into tx/rx queue
- class hwtLib.peripheral.usb.sim.agent_base.UsbPacketData(pid: int, data: List[int])[source]¶
Bases:
object
- class hwtLib.peripheral.usb.sim.usb_agent_device.UsbDevAgent(rx: Deque[Union[UsbPacketToken, UsbPacketData]], tx: Deque[Union[UsbPacketToken, UsbPacketData]], descriptors: UsbDescriptorBundle)[source]¶
Bases:
UsbAgent
This agent uses rx and tx queue to comunicate with a USB device. The agnet implements address assignment and descriptor upload and it is meant to be extended with a specific functionality of USB device.
- __init__(rx: Deque[Union[UsbPacketToken, UsbPacketData]], tx: Deque[Union[UsbPacketToken, UsbPacketData]], descriptors: UsbDescriptorBundle)[source]¶
- class hwtLib.peripheral.usb.sim.usb_agent_host.UsbHostAgent(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]¶
Bases:
UsbAgent
This agent uses rx and tx queue to comunicate with a USB device. It performs bus enumerations, sets address to a device and downloads the descriptors. Note that the agent is written in a way which allows for easy extension to a driver which can parse the specific descriptors and comunicate with devices further.
- __init__(rx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]], tx: Deque[Union[UsbPacketToken, UsbPacketData, UsbPacketHandshake]])[source]¶
- control_read(addr, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bRequest: int, wValue: int, wIndex: int, wLength: int, bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT = 0, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION = 1)[source]¶
- control_write(addr: int, ep: int, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bRequest: int, wValue: int, wIndex: int, buff: List[int], bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT = 0, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION = 0)[source]¶
- download_descriptor(addr: int, descriptor_t: ~typing.Union[~hwt.hdl.types.struct.HStruct, str], index: int, wIndex: int = 0, wLength: ~typing.Optional[int] = <class 'hwt.synthesizer.rtlLevel.constants.NOT_SPECIFIED'>)[source]¶
- get_max_packet_size(addr: int, endp: int, direction: USB_ENDPOINT_DIR)[source]¶
- parse_interface_functional_descriptor(interface_descr: StructValBase, data: BitsVal)[source]¶
- attention
on USB the LSB bits are sent first
- class hwtLib.peripheral.usb.constants.USB_LINE_STATE[source]¶
Bases:
object
- J = 1¶
- K = 2¶
- SE0 = 0¶
- SE1 = 3¶
- class hwtLib.peripheral.usb.constants.USB_PID[source]¶
Bases:
object
USB Protocol layer packet identifier values (Specifies the type of transaction)
- Attention
visualy written in msb-first, transmited in lsb first
- Note
packet formats are described in structs in this file
- Note
if the PID is in 8b format the other 4 bits (check field) are a bitwise inversion of original 4b PID field
- DATA_0 = 3¶
- DATA_1 = 11¶
- DATA_2 = 7¶
- DATA_M = 15¶
- ERR = 12¶
- HS_ACK = 2¶
- HS_NACK = 10¶
- HS_NYET = 6¶
- HS_STALL = 14¶
- PING = 4¶
- PREAMBLE = 12¶
- SPLIT = 8¶
- TOKEN_IN = 9¶
- TOKEN_OUT = 1¶
- TOKEN_SETUP = 13¶
- TOKEN_SOF = 5¶
- classmethod is_data(v: Union[int, RtlSignalBase])[source]¶
- classmethod is_hs(v: Union[int, RtlSignalBase])[source]¶
- classmethod is_token(v: Union[int, RtlSignalBase])[source]¶
- class hwtLib.peripheral.usb.constants.USB_VER[source]¶
Bases:
object
USB_VER
Speed
1.0 - 2.0
Low Speed 1.5 Mbit/s
1.0 - 2.0
Full Speed 12 Mbit/s
2.0
High Speed 480 Mbit/s
3.0
SuperSpeed 5Gbit/s
3.1
SuperSpeed+ 10Gbit/s
3.2
SuperSpeed+ 20Gbit/s
4.0
SuperSpeed+ 40Gbit/s
- USB1_0 = '1.0'¶
- USB1_1 = '1.1'¶
- USB2_0 = '2.0'¶
- USB3_0 = '3.0'¶
- USB3_1 = '3.1'¶
- USB3_2 = '3.2'¶
- USB4_0 = '4.0'¶
- values = ['1.0', '1.1', '2.0', '3.0', '3.1', '3.2', '4.0']¶
- hwtLib.peripheral.usb.constants.usb2_0_packet_data_t = struct { <Bits, 4bits> pid <HStream len:(1, 1024), align:(0,) <Bits, 8bits>> data <Bits, 16bits> crc }¶
There are three type of handshake packets which consist simply of the USB_PID
ACK - Acknowledgment that the packet has been successfully received.
NAK - Reports that the device temporary cannot send or received data. Also used during interrupt transactions to inform the host there is no data to send.
STALL - The device finds its in a state that it requires intervention from the host.
- hwtLib.peripheral.usb.constants.usb_packet_hs_t = struct { <Bits, 4bits> pid }¶
The SOF (Start of Frame) packet consisting of an 11-bit frame number is sent by the host every 1ms ± 500ns on a full speed bus or every 125 µs ± 0.0625 µs on a high speed bus.
- hwtLib.peripheral.usb.constants.usb_pid_t = <Bits, 4bits>¶
- Attention
every packet starts with sync and ends in EOP, which is not in data structures below
- class hwtLib.peripheral.usb.device_request.USB_REQUEST[source]¶
Bases:
object
Values for usb_device_request_t.bRequest
- CLEAR_FEATURE = 1¶
- GET_CONFIGURATION = 8¶
- GET_DESCRIPTOR = 6¶
- GET_INTERFACE = 10¶
- GET_STATUS = 0¶
- SET_ADDRESS = 5¶
- SET_CONFIGURATION = 9¶
- SET_DESCRIPTOR = 7¶
- SET_FEATURE = 3¶
- SET_INTERFACE = 17¶
- SYNCH_FRAME = 18¶
- class hwtLib.peripheral.usb.device_request.USB_REQUEST_TYPE_DIRECTION[source]¶
Bases:
object
Values for usb_request_type_t.recipient
- DEV_TO_HOST = 1¶
- HOST_TO_DEV = 0¶
- class hwtLib.peripheral.usb.device_request.USB_REQUEST_TYPE_RECIPIENT[source]¶
Bases:
object
Values for usb_request_type_t.data_transfer_direction
- DEVICE = 0¶
- ENDPOINT = 2¶
- INTERFACE = 1¶
- OTHER = 3¶
- class hwtLib.peripheral.usb.device_request.USB_REQUEST_TYPE_TYPE[source]¶
Bases:
object
Values for usb_request_type_t.type
- CLASS = 1¶
- STANDARD = 0¶
- VENDOR = 2¶
- hwtLib.peripheral.usb.device_request.make_usb_device_request(bmRequestType_recipient: USB_REQUEST_TYPE_RECIPIENT, bmRequestType_type: USB_REQUEST_TYPE_TYPE, bmRequestType_data_transfer_direction: USB_REQUEST_TYPE_DIRECTION, bRequest: USB_REQUEST, wValue: int, wIndex: int, wLength: int)[source]¶
hwtLib.sim package¶
Submodules¶
hwtLib.sim.abstractMemSpaceMaster module¶
- class hwtLib.sim.abstractMemSpaceMaster.AbstractMemSpaceMaster(bus, registerMap)[source]¶
Bases:
MemorySpaceItemStruct
Abstraction over bus interface which converts it to memory space from where you can read or write
- _read(addr, size, onDone=None)[source]¶
Add read transaction to agent of interface :param addr: address value on bus to read froms :param size: size of data to read in bites :param onDone: on read done callback function(sim) -> None
- class hwtLib.sim.abstractMemSpaceMaster.MemorySpaceItem(memHandler, transTmpl, offset=0)[source]¶
Bases:
object
Abstraction over place in memory, allows you read and write data to/from this space
- class hwtLib.sim.abstractMemSpaceMaster.MemorySpaceItemArr(memHandler, transTmpl, offset=0)[source]¶
Bases:
object
Abstraction over place in memory, allows you read and write data to/from this space
hwtLib.tools package¶
Submodules¶
hwtLib.tools.debug_bus_monitor_ctl module¶
- class hwtLib.tools.debug_bus_monitor_ctl.Colorizer[source]¶
Bases:
object
A base class for objects which looks at the data and resolves color of the output text/element
- class hwtLib.tools.debug_bus_monitor_ctl.ColorizerHandshakeOrEnLike[source]¶
Bases:
Colorizer
- LIGHT_GREEN = '#90ee90'¶
- LIGHT_PURPLE = '#b19cd9'¶
- LIGHT_RED = '#ffcccb'¶
- class hwtLib.tools.debug_bus_monitor_ctl.DebugBusMonitorCtl(addr)[source]¶
Bases:
object
A tool used to interact with a
hwtLib.abstract.debug_bus_monitor.DebugBusMonitor
- REG_DATA_MEMORY = 8¶
- REG_NAME_MEMORY_OFFSET = 4¶
- REG_NAME_MEMORY_SIZE = 0¶
- _dump_dot_link_set(meta_memory: List[VisualNodeTemplate], out: StringIO, indent: int) None [source]¶
- _dump_dot_node_set(meta_memory: List[VisualNodeTemplate], out: StringIO, colorizer: Colorizer, data: int, indent: int) None [source]¶
- construct_id_to_node_dict(meta_memory: List[VisualNodeTemplate], res: Dict[int, VisualNodeTemplate])[source]¶
- dump_dot(out=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, colorizer=<hwtLib.tools.debug_bus_monitor_ctl.ColorizerHandshakeOrEnLike object>) None [source]¶
- get_data_memory_width(meta_memory: Union[VisualNodeTemplate, list, List[int]])[source]¶
- class hwtLib.tools.debug_bus_monitor_ctl.DebugBusMonitorCtlDevmem(addr)[source]¶
Bases:
DebugBusMonitorCtl
- data_memory_size: Optional[int]¶
- meta_memory: Optional[VisualNodeTemplate]¶
- class hwtLib.tools.debug_bus_monitor_ctl.VisualNodeTemplate(id_: int, name: str, data_spec: list, parent: Optional[VisualNodeTemplate] = None)[source]¶
Bases:
object
- __init__(id_: int, name: str, data_spec: list, parent: Optional[VisualNodeTemplate] = None)[source]¶
- _default_dot_formatter(data: int, out: StringIO, indent: int, colorizer: Optional[Colorizer]) str [source]¶
Format interface signals and values as a html like table for graphwiz
- classmethod _default_txt_formatter(name: str, data_spec, children: List[VisualNodeTemplate], data: int, out: StringIO, indent: int)[source]¶
- hwtLib.tools.debug_bus_monitor_ctl.bit_mask(w)[source]¶
- Note
duplication with pyMathBitPrecise in order to keep this script without non-std dependencies
hwtLib.types package¶
Subpackages¶
hwtLib.types.net package¶
- class hwtLib.types.net.arp.ARP_HW_TYPE[source]¶
Bases:
object
- ARP_SEC = 32¶
- ETHERNET = 1¶
- FIBRE_CHANNEL = 18¶
- FRAME_RELAY = 15¶
- INIFNIBAND = 32¶
- IP_SEC_TUNNEL = 31¶
- class hwtLib.types.net.arp.ARP_OPTCODE[source]¶
Bases:
object
- ARP_NAK = 10¶
- IN_ARP_REPLY = 9¶
- IN_ARP_REQUEST = 8¶
- MAPOS_UNARP = 23¶
- class MARS[source]¶
Bases:
object
- GROUPLIST_REPLY = 21¶
- GROUPLIST_REQUEST = 20¶
- JOIN = 14¶
- LEAVE = 15¶
- MSERV = 13¶
- MULTI = 12¶
- NAK = 16¶
- REDIRECT_MAP = 22¶
- REQUEST = 11¶
- SJOIN = 18¶
- SLEAVE = 19¶
- UNSERV = 17¶
- OP_EXP1 = 24¶
- OP_EXP2 = 25¶
- REPLY = 2¶
- REQUEST = 1¶
- REQUEST_REVERSE = 3¶
- class hwtLib.types.net.ip.IP_PROTOCOL[source]¶
Bases:
object
- EGP = 8¶
- ENCAP = 41¶
- ETHERIP = 97¶
- GGP = 3¶
- HOPOPT = 0¶
- ICMP = 1¶
- IGMP = 2¶
- IGP = 9¶
- IPIP = 94¶
- IPv4 = 4¶
- IPv6_ICMP = 58¶
- IPv6_frag = 44¶
- IPv6_noNxt = 59¶
- IPv6_opts = 60¶
- IPv6_route = 43¶
- L2TP = 115¶
- OSPF = 89¶
- QNX = 106¶
- SCTP = 132¶
- SMP = 121¶
- TCP = 6¶
- UDP = 17¶
Submodules¶
hwtLib.types.ctypes module¶
hwtLib.xilinx package¶
Subpackages¶
hwtLib.xilinx.primitive package¶
- class hwtLib.xilinx.primitive.examples.dsp48e1Add.Dsp48e1Add(hdl_name_override: Optional[str] = None)[source]¶
Bases:
Unit
- class hwtLib.xilinx.primitive.examples.dsp48e1Add.Dsp48e1AluInput(masterDir=DIRECTION.OUT, hdl_name: Optional[Union[str, Dict[str, str]]] = None, loadConfig=True)[source]¶
Bases:
HandshakeSync
- class hwtLib.xilinx.primitive.examples.dsp48e1Add.Dsp48e1AluInputAG(sim: HdlSimulator, intf: Handshaked, allowNoReset=False)[source]¶
Bases:
HandshakedAgent
- hwtLib.xilinx.primitive.examples.dsp48e1Add.generate_handshake_pipe_cntrl(parent: Unit, n: int, name_prefix: str, in_valid: RtlSignal, out_ready: RtlSignal)[source]¶
An utility that construct a pipe of registers to store the validity status of a register in the pipeline. These registers are connected in pipeline and synchronized by handshake logic. Clock enable signal for each stage in pipeline is also provided.
- Variables
~.n – number of stages
- class hwtLib.xilinx.primitive.dsp48e1_constants.CARRYIN_SEL(value)[source]¶
Bases:
Enum
An enumeration.
- A_27_eq_B_17 = 6¶
- CARRYCASCIN = 2¶
- CARRYCASCOUT = 4¶
- CARRYIN = 0¶
- PCIN_47 = 3¶
- PCIN_47_n = 1¶
- P_47 = 7¶
- P_47_n = 5¶
- class hwtLib.xilinx.primitive.dsp48e1_constants.MUL_A_SEL(value)[source]¶
Bases:
Enum
An enumeration.
- A1 = 1¶
- A2 = 0¶
- D = 5¶
- D_MINUS_A1 = 9¶
- D_MINUS_A2 = 8¶
- D_PLUS_A1 = 4¶
- D_PLUS_A2 = 3¶
- MINUS_A1 = 7¶
- MINUS_A2 = 6¶
- ZERO = 2¶
- class hwtLib.xilinx.primitive.dsp48e1_constants.MUL_B_SEL(value)[source]¶
Bases:
Enum
An enumeration.
- B1 = 1¶
- B2 = 0¶
- class hwtLib.xilinx.primitive.dsp48e1_constants.X_SEL(value)[source]¶
Bases:
Enum
An enumeration.
- A_B = 3¶
- M = 5¶
- P = 2¶
- ZERO = 0¶
- class hwtLib.xilinx.primitive.dsp48e1_constants.Y_SEL(value)[source]¶
Bases:
Enum
An enumeration.
- C = 12¶
- M = 5¶
- MINUS_1 = 8¶
- ZERO = 0¶
- class hwtLib.xilinx.primitive.dsp48e1_constants.Z_SEL(value)[source]¶
Bases:
Enum
An enumeration.
- C = 48¶
- P = 32¶
- PCIN = 16¶
- PCIN_SHIFT_17b = 80¶
- P_MACC = 72¶
- P_SHIFT_17b = 96¶
- ZERO = 0¶
- class hwtLib.xilinx.primitive.lutAsShiftReg.LutAsShiftReg(hdl_name_override: Optional[str] = None)[source]¶
Bases:
Unit
This components generates SRL16E and other shift registers.
In order to allow Xilinx Vivado 2020.2 (and possibly any other version) to map this component into SRL16E and equivalents we need to satisfy several conditions: 1. the memory must not have reset 2. the shift expressions must be performed on a single signal 3. whole memory must be single signal 4. the output must be read only by index operator (switch on address does not work) 5. we can not merge memories of individual data bits
- class hwtLib.xilinx.primitive.mmcme2.MMCME2_ADV(hdl_name_override: Optional[str] = None)[source]¶
Bases:
Unit
Mixed-Mode Clock Manager (PLL like frequency synchronizer/clock generator) on Xilinx 7+ series
https://www.xilinx.com/support/documentation/user_guides/ug472_7Series_Clocking.pdf
Submodules¶
hwtLib.xilinx.constants module¶
hwtLib.xilinx.platform module¶
- class hwtLib.xilinx.platform.XilinxVivadoPlatform(part: Optional[str] = None)[source]¶
Bases:
DummyPlatform
hwtLib.xilinx.slr_crossing module¶
- class hwtLib.xilinx.slr_crossing.HsSlrCrossing(hdl_name_override: Optional[str] = None)[source]¶
Bases:
HsSlrCrossingIo
Super Logic Region (SLR) crossing for handshaked interfaces
SLR represents one chiplet of FPGA which uses stacked silicon interconnect (SSI) or equivalent. The SLR corssing is required on SLR boundaries to met the timing. The crossing itself is just a pipeline of registers.
- class hwtLib.xilinx.slr_crossing.HsSlrCrossingIo(hdl_name_override: Optional[str] = None)[source]¶
Bases:
BusBridge
An abstract class with a declaration of interfaces for handskaked SLR crosings
- class hwtLib.xilinx.slr_crossing.SlrCrossingDst(hdl_name_override: Optional[str] = None)[source]¶
Bases:
HsSlrCrossingIo
A part of SLR crossing which should be placed in SLR of consumer
- class hwtLib.xilinx.slr_crossing.SlrCrossingSrc(hdl_name_override: Optional[str] = None)[source]¶
Bases:
HsSlrCrossingIo
A part of SLR crossing which should be placed in SLR of producer