Modules

class trgenpy.trgen.TrgenPort(id, memory_length=32)[source]

Class representing a trigger generator port (TrgenPort). A TrgenPort is identified by its ID and has a specific memory length.

Parameters:
  • id (int) – The ID of the trigger (0-25).

  • memory_length (int) – The length of the trigger memory (2^mtml).

id

The ID of the trigger (0-25).

Type:

int

memory_length

The length of the trigger memory (1-64).

Type:

int

type

The type of the trigger (NeuroScan, Synamps, BNCO, BNCI, GPIO).

Type:

str

memory

The list of instructions in the trigger memory.

Type:

list

Raises:
  • ValueError – If id or memory_length is out of allowed range.

  • TypeError – If id or memory_length is not an integer.

Example

from trgenpy import TrgenPort

# Create a TrgenPort with ID 0 and memory length of 32
trgen_port = TrgenPort(id=0, memory_length=32)
print(trgen_port)
property id

Get the ID of the trgen.

setInstruction(index, instruction)[source]

Set an instruction at a specific index in the trigger memory. :param index: The index in the trigger memory to set the instruction. :type index: int :param instruction: The instruction to set. :type instruction: int

Raises:

IndexError – If the index is out of bounds.

Example

trgen_port = TrgenPort(id=0, memory_length=32)
trgen_port.setInstruction(0, 123)
exception trgenpy.connection.AckFormatError(ack_str)[source]

Raised when the ACK response format is incorrect.

class trgenpy.connection.DirectionConfig[source]

Class to configure GPIO directions.

Example

config = DirectionConfig().output(TrgenPin.GPIO0, TrgenPin.GPIO1).input(TrgenPin.GPIO2).build()
client.set_gpio_direction(config)
static encode_direction(levels: dict[TrgenPin, GPIODirection]) int[source]

Encodes GPIO directions into a bitmask.

  • 1: Output

  • 0: Input

Parameters:

levels (dict) – Dictionary mapping TrgenPin to GPIODirection (IN/OUT).

Returns:

Bitmask to pass to client.set_gpio_direction()

Return type:

int

Example

levels = {
    TrgenPin.GPIO0: GPIODirection.OUT,
    TrgenPin.GPIO1: GPIODirection.IN,
    TrgenPin.GPIO2: GPIODirection.OUT,
}
mask = DirectionConfig.encode_direction(levels)
exception trgenpy.connection.InvalidAckError(expected, received)[source]

Raised when an invalid ACK response is received from the Trgen.

exception trgenpy.connection.InvalidPinError[source]

Raised when a non-GPIO pin is used for GPIO configuration.

class trgenpy.connection.LevelConfig[source]

Class to configure trigger levels.

Example

from trgenpy import TrgenClient, TrgenPin

client = TrgenClient()
client.connect()

# Configura NS0 e SA1 come HIGH, GPIO0 come LOW
config = LevelConfig().high(TrgenPin.NS0, TrgenPin.SA1).low(TrgenPin.GPIO0).build()
client.set_level(config)
static encode_levels(levels: dict[TrgenPin, TrgenLevel]) int[source]

levels: dizionario {pin: TrgenLevel.HIGH/LOW} ritorna: bitmask da passare a client.set_level()

class trgenpy.connection.TrgenClient(ip='192.168.123.1', port=4242, timeout=2.0, default_trigger_duration_us=20)[source]

Client used to communicate with TrgenPort Devices via TCP/IP sockets.

ip

IP address of the device, default is ‘192.168.123.1’

Type:

str

port

Communication port, default is 4242.

Type:

int

timeout

Timeout for the connection in seconds.

Type:

float

default_trigger_duration_us

Default trigger duration in microseconds.

Type:

int

Raises:
  • InvalidAckError – If the ACK response is invalid.

  • AckFormatError – If the ACK response is malformed.

  • TimeoutError – If the connection times out.

Example

from trgenpy import TrgenClient, TrgenPin

client = TrgenClient()
callbackCustomTrigger(ne=False, trgenPinList=None, inputPin=None, customInstructions=None)[source]

Send a custom trigger signal out of the BNC (BNCO).

Parameters:
  • triggerList (list of TrgenPin) – List of TrgenPin to be triggered, when None uses BNCO.

  • inputPin (TrgenPin) – ID del pin di input (BNCI o GPIO)

  • ne (bool) – Se True, attende fronte negativo; se False, fronte positivo

  • customInstructions (list of Instruction, optional) – List of custom instructions to set for each trigger.

Raises:
  • ValueError – If triggerList is not a list of TrgenPin or is empty.

  • ValueError – If inputPin is not a valid TrgenPin.

Example

from trgenpy import TrgenClient, TrgenPin, istrActiveFor, istrUnactiveFor, istrEnd
client = TrgenClient()
client.connect()
client.callbackCustomTrigger(
    ne=False,
    trgenPinList=[TrgenPin.NS0, TrgenPin.SA1],
    inputPin=TrgenPin.BNCI,
    customInstructions=[
        istrActiveFor(50),
        istrUnactiveFor(50),
        istrEnd()
    ]
)
callbackMarker(markerNS=0, markerSA=0, markerGPIO=0, LSB=False, inputPin=None, ne=False)[source]

Callback for marker to NS, SA and/or GPIO connectors based on input trigger.

Parameters:
  • markerNS (int, optional) – Marker for NeuroScan.

  • markerSA (int, optional) – Marker for Synamps.

  • markerGPIO (int, optional) – Marker for GPIO.

  • inputPin (TrgenPin) – ID del pin di input (BNCI o GPIO)

  • LSB (bool, optional) – If True, use the least significant bit first.

  • ne (bool) – Se True, attende fronte negativo; se False, fronte positivo

Raises:

ValueError – If inputPin is not a valid TrgenPin.

Example

from trgenpy import TrgenClient, TrgenPin
client = TrgenClient()
client.connect()
client.callbackMarker(
    markerNS=5,
    markerSA=3,
    markerGPIO=12,
    inputPin=TrgenPin.BNCI,
    LSB=True,
    ne=False
)
connect()[source]

Connect to the Trgen and retrieve its implementation details.

Raises:
  • InvalidAckError – If the ACK response is invalid.

  • AckFormatError – If the ACK response is malformed.

  • TimeoutError – If the connection times out.

createTrgenPort(trigger_id: TrgenPin, instruction_set=None) TrgenPort[source]

Create a TrgenPort object for the specified trigger ID. :param trigger_id: ID of the trigger to create. :type trigger_id: TrgenPin

Raises:

ValueError – If trigger_id is not a valid TrgenPin value.

Returns:

The created TrgenPort object.

Return type:

TrgenPort

Example

client = TrgenClient()
trgen_port = client.createTrgenPort(TrgenPin.NS0)
print(trgen_port)
disable_trigger(trgenport)[source]

Disable a specific trgenport by sending a default program that ends immediately.

getDefaultDuration() int[source]

Get the current default trigger duration in microseconds.

Returns:

Default duration in microseconds

Return type:

int

getImplementation()[source]

Get current implementation for Trgen :returns: Implementation details of the connected Trgen. :rtype: TrgenImplementation

Raises:
  • InvalidAckError – If the ACK response is invalid.

  • AckFormatError – If the ACK response is malformed.

  • TimeoutError – If the connection times out.

getTresholdValue(photod_num: int)[source]

Get the threshold value for a specific photodiode.

Sends a trgen_thr_t struct with photod_num set; the device responds with a uint32_t where:

  • bits 0-15 → threshold value

  • bit 16 → trigger flag

Parameters:

photod_num (int) – Photodiode index (0-based).

Returns:

{'photod_num': int, 'threshold': int, 'trigger': bool}

Return type:

dict

Example

result = client.getTresholdValue(0)
print(result['threshold'], result['trigger'])
get_gpio_direction()[source]

Get current direction for GPIO

get_level()[source]

Get the trigger active polarity

get_status()[source]

Get current State for all triggers

is_available()[source]

Verifica se il dispositivo TrgenPort è raggiungibile.

Returns:

True se il dispositivo risponde, False altrimenti.

Return type:

bool

programDefaultTrigger(trgenport, us=None)[source]

Program one trigger (by Id) with a default pulse.

Parameters:
  • trgenport (TrgenPort) – TrgenPort object to program.

  • us (int, optional) – duration of the pulse in microseconds. If None, uses the client’s default duration.

resetAllTrgenPorts()[source]

Reset all triggers to a safe state.

resetTrgenPort(trgenport)[source]

Reset a specific trigger to a safe state.

sendMarker(markerNS=0, markerSA=0, markerGPIO=0, LSB=False, stop=True, autoStart=True)[source]

Send a marker to NS, SA and/or GPIO connectors.

Parameters:
  • markerNS (int, optional) – Marker for NeuroScan.

  • markerSA (int, optional) – Marker for Synamps.

  • markerGPIO (int, optional) – Marker for GPIO.

  • LSB (bool, optional) – If True, use the least significant bit first.

  • stop (bool, optional) – If True, stop the trigger sequence after sending.

  • autoStart (bool, optional) – If True, start the trigger sequence automatically.

sendTrigger(trgenPinList=None, autoStart=True)[source]

Send a custom trigger signal out of the BNC (BNCO). :param triggerList: List of TrgenPin to be triggered. :type triggerList: list of TrgenPin

setDefaultDuration(duration_us: int)[source]

Set the default trigger duration in microseconds.

Parameters:

duration_us (int) – Duration in microseconds

setTresholdValue(photod_num: int, threshold: int)[source]

Set the threshold value for a specific photodiode.

Sends a trgen_thr_t struct with photod_num and threshold in network byte order (equivalent to C htons()).

Parameters:
  • photod_num (int) – Photodiode index (0-based).

  • threshold (int) – Threshold value to set (uint16).

Example

client.setTresholdValue(0, 512)
setTrgenPortInstructions(trgenport: TrgenPort, instruction_set)[source]

Set a complete instruction set to a TrgenPort.

This method automatically handles: - Setting each instruction in sequence - Adding istrNotAdmissible() for remaining memory slots - Memory bounds validation

Parameters:
  • trgenport (TrgenPort) – The TrgenPort to program.

  • instruction_set (List[int]) – List of instructions to set. Must end with istrEnd().

Raises:
  • ValueError – If instruction_set is empty, too long, or doesn’t end with istrEnd().

  • TypeError – If trgenport is not a TrgenPort instance.

Example

instruction_set = [
    istrWaitPE(TrgenPin.BNCI),
    istrActiveFor(50),
    istrUnactiveFor(10),
    istrEnd()
]

bnco = client.createTrgenPort(TrgenPin.BNCO)
client.setTrgenPortInstructions(bnco, instruction_set)
client.writeTrgenMemory(bnco)
set_gpio_direction(gpio_mask)[source]

Set the direction (bitmask da 0 a 7) for GPIO

Parameters:

gpio_mask (int) – Bitmask representing the desired GPIO directions (1=output, 0=input).

Raises:

ValueError – If gpio_mask is not in the range 0-0xFF (8 bits).

Returns:

None

Example

client = TrgenClient()
client.set_gpio_direction(0b00001111)  # GPIO0-3 ON, GPIO4-7 OFF
set_level(level_mask)[source]

Set the trigger polarity (bitmask: 1 = active high, 0 = active low)

Parameters:

level_mask (int) – Bitmask representing the desired levels for each trigger pin.

Raises:
  • ValueError – If level_mask is not in the range 0-0x03FFFFFF (26 bits).

  • ValueError – If level_mask is not in the range 0-0x03FFFFFF (26 bits).

Example

client = TrgenClient()
level_mask = 0b00000000000000000000000011  # NS0 and NS1 HIGH, others LOW
client.set_level(level_mask)
start()[source]

Start the execution of triggers on the device.

startCalibration(count: int = 1)[source]

Start the calibration process and read back the calibrated threshold values.

Sends CMD_START_CALIBRATION with no payload, waits 100 ms for the hardware to complete the calibration, then reads back the threshold value for each photodiode via getTresholdValue.

Parameters:

count (int) – Number of photodiodes to read back after calibration. Defaults to 1.

Returns:

List of {'photod_num', 'threshold', 'trigger'} dicts,

one per photodiode.

Return type:

list[dict]

Example

results = client.startCalibration(count=4)
for r in results:
    print(r['photod_num'], r['threshold'], r['trigger'])
stop()[source]

Stop the execution of triggers on the device.

writeTrgenMemory(trgenport: TrgenPort)[source]

Send the memory bank of one pre-programmed trigger Pin to the TrgenPort device.

Parameters:

trgenport (TrgenPort) – Object to send.

Raises:
  • TypeError – If trgenport is not a TrgenPort instance.

  • ValueError – If trgenport.id is not a valid TrgenPin value.

Returns:

None

Example

trgen_port = TrgenPort(id=0, memory_length=32)
# Populate trgen_port.memory with instructions...
client.writeTrgenMemory(trgen_port)
trgenpy.crc.compute_crc32(data: bytes) int[source]

Compute the CRC32 checksum of the given data.

Parameters:

data (bytes) – Input data to compute the CRC32 checksum for.

Returns:

The computed CRC32 checksum as an unsigned 32-bit integer.

Return type:

int

class trgenpy.implementation.TrgenImplementation(ns_num, sa_num, bnco_num, bnci_num, gpio_num, photod_num, spiif, spi_res, mtml)[source]

Class to represent the Trgen implementation details.

classmethod from_packed_value(value: int)[source]

Create an instance from a packed integer value.

property memory_length

Returns the memory length required for the triggers.

property mtml

Get the memory length exponent (mtml).

property spi_res

Get the SPI resolution.

property total_triggers

Returns the total number of triggers.

trgenpy.instruction.decode_instruction(word)[source]

Decodes an instruction word into its type and parameters.

Parameters:

word (int) – Encoded instruction word.

Returns:

(instruction_type (str), parameters (any))
  • For ‘UNACTIVE’ and ‘ACTIVE’: (type, duration)

  • For ‘WAIT_PE’ and ‘WAIT_NE’: (type, trigger pin)

  • For ‘REPEAT’: (type, {‘addr’: addr, ‘times’: times})

  • For ‘END’: (type, None)

  • For unknown: (‘UNKNOWN’, None)

Return type:

tuple

trgenpy.instruction.istrActiveFor(x)[source]

Encodes an ‘active’ instruction for a given number of microseconds.

Parameters:

x (int) – Duration in microseconds.

Returns:

Encoded instruction word.

Return type:

int

trgenpy.instruction.istrEnd()[source]

Encodes an ‘istrEnd’ instruction.

Returns:

Encoded instruction word.

Return type:

int

trgenpy.instruction.istrNotAdmissible()[source]

Encodes a ‘not admissible’ instruction.

Returns:

Encoded instruction word.

Return type:

int

trgenpy.instruction.istrRepeat(addr, times)[source]

Encodes a ‘istrRepeat’ instruction to istrRepeat a sequence.

Parameters:
  • addr (int) – Address to istrRepeat from.

  • times (int) – Number of repetitions.

Returns:

Encoded instruction word.

Return type:

int

trgenpy.instruction.istrUnactiveFor(x)[source]

Encodes an ‘unactive’ instruction for a given number of microseconds.

Parameters:

x (int) – Duration in microseconds.

Returns:

Encoded instruction word.

Return type:

int

trgenpy.instruction.istrWaitNE(tr)[source]

Encodes a ‘wait for negative edge’ instruction on a trigger pin.

Parameters:

tr (int) – TrgenPort pin identifier.

Returns:

Encoded instruction word.

Return type:

int

trgenpy.instruction.istrWaitPE(tr)[source]

Encodes a ‘wait for positive edge’ instruction on a trigger pin.

Parameters:

tr (int) – TrgenPort pin identifier.

Returns:

Encoded instruction word.

Return type:

int

class trgenpy.trgen_pin.GPIODirection(value)[source]

Enum for the GPIO directions. GPIO can be configured as input or output.

class trgenpy.trgen_pin.TrgenLevel(value)[source]

Enum for the trigger levels. A trigger can be set to HIGH or LOW level.

class trgenpy.trgen_pin.TrgenPin(value)[source]

Enum for the trigger pins.

Represents various trigger pins available on the device. Pins NS0 to NS7, SA0 to SA7, BNCO, BNCI, and GPIO0 to GPIO7 are defined.

Code values correspond to pin identifiers:

  • 0-7: NS0 to NS7

  • 8-15: SA0 to SA7

  • 16: BNCO

  • 17: BNCI

  • 18-25: GPIO0 to GPIO7

  • 26: FOTODIODO

Example

pin = TrgenPin.NS0
if pin == TrgenPin.NS0:
    print("Selected pin is NS0")

TrGEN Configuration Management for Python

This module provides classes and utilities for exporting and importing TrGEN configurations to/from JSON files with .trgen extension. It supports full trigger port configurations including memory instructions, network settings, and metadata.

Classes:

TrgenConfiguration: Main configuration container ConfigurationMetadata: Configuration file metadata DefaultSettings: Default trigger settings TriggerPortConfig: Individual trigger port configuration NetworkSettings: Network connection settings PortProgrammingState: Enumeration for port programming states

class trgenpy.configuration.ConfigurationMetadata[source]

Metadata for TrGEN configuration files. Contains information about the configuration file such as version, dates, author, etc.

classmethod from_dict(data: Dict[str, Any]) ConfigurationMetadata[source]

Create metadata instance from dictionary.

to_dict() Dict[str, Any][source]

Convert metadata to dictionary for JSON serialization.

class trgenpy.configuration.DefaultSettings[source]

Default settings for all triggers in the configuration. Contains global default values that apply to all trigger ports.

classmethod from_dict(data: Dict[str, Any]) DefaultSettings[source]

Create default settings instance from dictionary.

to_dict() Dict[str, Any][source]

Convert default settings to dictionary for JSON serialization.

class trgenpy.configuration.NetworkSettings[source]

Network configuration settings for TrGEN device connection. Contains IP address, port, and timeout settings.

classmethod from_dict(data: Dict[str, Any]) NetworkSettings[source]

Create network settings instance from dictionary.

to_dict() Dict[str, Any][source]

Convert network settings to dictionary for JSON serialization.

class trgenpy.configuration.PortProgrammingState(value)[source]

Represents the programming state of a trigger port.

class trgenpy.configuration.TrgenConfiguration[source]

Main configuration class that contains all TrGEN settings. This is the root configuration object that gets serialized to/from JSON files.

classmethod from_dict(data: Dict[str, Any]) TrgenConfiguration[source]

Create configuration instance from dictionary.

to_dict() Dict[str, Any][source]

Convert configuration to dictionary for JSON serialization.

class trgenpy.configuration.TriggerPortConfig(memory_length: int = 32)[source]

Configuration for a specific trigger port. Contains all the information needed to configure and program a single trigger port, including its memory instructions and settings.

apply_to_trgen_port(trgen_port)[source]

Apply this configuration to a TrgenPort object.

Parameters:

trgen_port – TrgenPort instance to apply configuration to

classmethod from_dict(data: Dict[str, Any]) TriggerPortConfig[source]

Create trigger port config instance from dictionary.

get_instructions_string() str[source]

Get a string representation of the programmed instructions.

has_programmed_instructions() bool[source]

Check if the port has programmed instructions.

set_memory_from_trgen_port(trgen_port)[source]

Set the memory content from a TrgenPort object.

Parameters:

trgen_port – TrgenPort instance to copy memory from

to_dict() Dict[str, Any][source]

Convert trigger port config to dictionary for JSON serialization.

TrGEN Configuration Manager

This module provides utilities for exporting and importing TrGEN configurations to/from JSON files with .trgen extension. It manages the complete lifecycle of configuration files including creation, loading, saving, and validation.

The configuration files use JSON format with custom .trgen extension for easy identification and maximum compatibility.

class trgenpy.configuration_manager.TrgenConfigurationManager[source]

Manages the export and import of TrGEN configurations in JSON format. Supports files with custom .trgen extension for easy identification. Uses native JSON for maximum compatibility without external dependencies.

static apply_port_configurations_selective(client, config: TrgenConfiguration, port_filters: List[str] = None) int[source]

Apply configuration only to selected ports and program them to hardware.

Parameters:
  • client – TrgenClient instance to apply configuration to

  • config – Configuration containing port settings

  • port_filters – List of port keys to apply (e.g., [‘NS0’, ‘SA1’]). If None, applies all enabled ports.

Returns:

Number of ports successfully programmed

Return type:

int

Raises:

ValueError – If client is None

static export_configuration(client, file_path: str, project_name: str = '', description: str = '', author: str = '') str[source]

Export the current TrGEN client configuration to a .trgen file (JSON format).

Parameters:
  • client – TrgenClient instance to export configuration from

  • file_path – File path (without extension or with .trgen)

  • project_name – Name of the project/experiment

  • description – Description of the configuration

  • author – Author of the configuration

Returns:

Complete path of the saved file

Return type:

str

Raises:
  • ValueError – If client is None

  • IOError – If file cannot be written

static import_configuration(client, file_path: str, apply_network_settings: bool = False) TrgenConfiguration[source]

Import a configuration from a .trgen file and apply it to the client.

Parameters:
  • client – TrgenClient instance to apply configuration to

  • file_path – Path to the .trgen file to import

  • apply_network_settings – Whether to apply network settings

Returns:

The imported configuration

Return type:

TrgenConfiguration

Raises:
  • ValueError – If client is None

  • FileNotFoundError – If configuration file doesn’t exist

  • ValueError – If file doesn’t have .trgen extension

  • ValueError – If configuration cannot be deserialized

static list_configuration_files(directory: str, recursive: bool = False) List[str][source]

List all .trgen files in a directory.

Parameters:
  • directory – Directory to search in

  • recursive – Whether to search recursively in subdirectories

Returns:

List of .trgen file paths found

Return type:

List[str]

static load_configuration(file_path: str) TrgenConfiguration[source]

Load a configuration from file without applying it to any client.

Parameters:

file_path – Path to the .trgen file

Returns:

The loaded configuration

Return type:

TrgenConfiguration

Raises:
  • FileNotFoundError – If configuration file doesn’t exist

  • ValueError – If file doesn’t have .trgen extension

  • ValueError – If configuration cannot be deserialized

static save_configuration(config: TrgenConfiguration, file_path: str) str[source]

Save a configuration to a .trgen file.

Parameters:
  • config – Configuration to save

  • file_path – Path to save the file to

Returns:

Complete path of the saved file

Return type:

str

Raises:

IOError – If file cannot be written