Skip to content

Hardware Link (caen.comm)

caen.comm

Low-level communication interface for CAEN digitizers via libCAENComm.

TheBoard

Wrapper around libCAENComm for register I/O and block data readout.

Supports context-manager usage (with TheBoard(...) as board:) to automatically open and close the hardware link.

Attributes:

Name Type Description
LinkTypes tuple[str, ...]

Supported physical link types ('USB', 'Optical').

ErrorCode dict[int, str | bool]

Mapping of CAENComm return codes to messages.

clib CDLL

Loaded CAENComm library handle (CAENComm.dll on Windows, libCAENComm.so on Linux).

NChannels int

Number of input channels on the digitizer (2 for DT5780).

ADCNbits int

Nominal ADC resolution in bits (14).

BufferSize int

Size of the MBLT readout buffer in 32-bit words (2**19).

ReadOutBuffer Array

Pre-allocated c_uint32 array for MBLT transfers.

BoardInfo dict[str, str]

Hardware model, serial number, and firmware metadata.

Source code in caen/comm.py
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
class TheBoard:
    """Wrapper around ``libCAENComm`` for register I/O and block data readout.

    Supports context-manager usage (``with TheBoard(...) as board:``) to
    automatically open and close the hardware link.

    Attributes:
        LinkTypes (tuple[str, ...]): Supported physical link types (``'USB'``, ``'Optical'``).
        ErrorCode (dict[int, str | bool]): Mapping of ``CAENComm`` return codes to messages.        
        clib (ct.CDLL): Loaded CAENComm library handle (``CAENComm.dll`` on Windows, ``libCAENComm.so`` on Linux).
        NChannels (int): Number of input channels on the digitizer (``2`` for DT5780).
        ADCNbits (int): Nominal ADC resolution in bits (``14``).
        BufferSize (int): Size of the MBLT readout buffer in 32-bit words (``2**19``).
        ReadOutBuffer (ct.Array): Pre-allocated ``c_uint32`` array for MBLT transfers.
        BoardInfo (dict[str, str]): Hardware model, serial number, and firmware metadata.
    """

    LinkTypes = ('USB', 'Optical')
    ErrorCode = { 0  : True,
                 -1  : 'VME Bus Error',
                 -2  : 'Communication Error',
                 -3  : 'Generic Error',
                 -4  : 'Invalid Parameter',
                 -5  : 'Invalid Link Type',
                 -6  : 'Invalid Handler',
                 -7  : 'Communication Timeout',
                 -8  : 'Device Not Found', 
                 -9  : 'Max Devices Error',
                 -10 : 'Device Already Open',
                 -11 : 'Not Supported',
                 -12 : 'Unused Bridge',
                 -13 : 'Terminated by Device',
                 -14 : 'Unsupported Base Address',}

    if sys.platform == "win32":
        clib = ct.WinDLL("CAENComm.dll")
    else:
        clib = ct.CDLL("libCAENComm.so")
#    clib = ct.cdll.LoadLibrary("libCAENComm.so")
    NChannels = 2      # number of channels
    ADCNbits  = 14     # how to get this from the board ?
    BufferSize = 1<<19

    def __init__(self, LinkNum=0, LinkType='USB'):
        """Initialize board communication parameters and allocate readout buffer.

        Args:
            LinkNum (int): USB or optical link index. Defaults to ``0``.
            LinkType (str): Physical connection type (``'USB'`` or ``'Optical'``).
        """
        self.LinkNum   = LinkNum
        self.LinkType  = LinkType
        self.handle    = ct.c_int(-1)
        self.ReadOutBuffer = (ct.c_uint32 * self.BufferSize)()
        self.BoardInfo = {}
        self.Reset = staticmethod(lambda: self.Reg32(0xEF24, 1))

    def __enter__(self):
        self.OpenLink(LinkNum=self.LinkNum, LinkType=self.LinkType)
        return self

    def __exit__(self, *args):
        self.CloseLink()

    def OpenLink(self, LinkNum=0, LinkType='USB'):
        """Open a communication link to the digitizer and query board metadata.

        Args:
            LinkNum (int): USB or optical link index.
            LinkType (str): Connection type (``'USB'`` or ``'Optical'``).

        Raises:
            ValueError: If ``CAENComm_OpenDevice2`` returns a non-zero error code.
        """
        LinkNum   = ct.byref(ct.c_uint32(LinkNum))
        LinkType  = self.LinkTypes.index(LinkType)
        R = self.clib.CAENComm_OpenDevice2(LinkType, LinkNum, 0, 0, ct.byref(self.handle))
        if R==0:
            self.GetBoardInfo()
        else:
            raise ValueError(self.ErrorCode[R])

    def CloseLink(self) -> bool | str:
        """Close the active ``CAENComm`` device handle.

        Returns:
            ``True`` on success, or an error description string.
        """

        R = self.ErrorCode[self.clib.CAENComm_CloseDevice(self.handle)]
        print(f"Close Device: {R}")        
        return R


    def Reg32(self, addr, data=None) -> int | str:
        """Read or write a 32-bit hardware register.

        Args:
            addr (int): Register address (e.g., ``0x8000``).
            data (int | None): Value to write. If ``None``, performs a 32-bit read.

        Returns:
            Register value on read success, status code on write, or error string on failure.
        """
        if data is not None:
            return self.clib.CAENComm_Write32(self.handle, ct.c_uint32(addr), ct.c_uint32(data))
        else:
            data = ct.c_uint32()
            R = self.clib.CAENComm_Read32(self.handle, ct.c_uint32(addr), ct.byref(data))
            return data.value if R==0 else self.ErrorCode[R]

    def ReadData(self) -> int:
        """Perform a Multi-Block Transfer (MBLT) readout into ``ReadOutBuffer``.

        Returns:
            Number of 32-bit words read from the digitizer memory.
        """
        nw = ct.c_int()
        R = self.clib.CAENComm_MBLTRead(self.handle, 0, self.ReadOutBuffer, self.BufferSize, ct.byref(nw))
#        print(f"Got {nw.value} samples!")
        if R!=0 and R!=-13:
            print(R, self.ErrorCode[R])
        return nw.value 

    def GetInfoHV(self) -> str:
        """Detect the installed High-Voltage Power Supply (HVPS) sub-module type.

        Temporarily enters HVPS identification mode via register ``0x1234`` and
        restores the original register state in a ``finally`` block.

        Returns:
            HVPS model suffix (``''`` for 5 kV, ``'SC'`` for 4 kV, ``'SD'`` for 0.5 kV,
                or ``'_'`` if unrecognized).
        """
        HV = (  '',       # 5kV 0.3mA
                'SC',     # 4kV   3mA 4W max
                'SD')     # 0.5kV 3mA
        n = None
        value = self.Reg32(0x1234)             # 0)
        try:
            self.Reg32(0x1234, value | 0x80)   # 1)
            sleep(0.1)                         # 2)
            version = self.Reg32(0x1238)       # 3)
            if version>=0x200:                 # 4)
                self.Reg32(0x1234, 0xB7)       # 5)
                sleep(0.1)                     # 6)
                n = self.Reg32(0x1240)         # 7)
        finally:
            self.Reg32(0x1234, value)          # 8)
            sleep(0.1)                         # 9)
        if n is not None and 0 <= n < len(HV):
            return HV[n]
        else:
            print('ask CAEN for support')
            return '_'

    def GetBoardInfo(self):
        """Read Configuration ROM and FPGA firmware registers to populate ``BoardInfo``.

        Also configures HVPS polarity signs (``HV_POLA``) and voltage/current
        step scaling factors (``HV_Vmax``, ``HV_Vset``, ``HV_Iset``).
        """
        bits = lambda x, bit, size: (x>>bit)&((1<<size)-1)
        C = lambda x: f'{bits(x,8,8):03d}.{bits(x,0,8):<3d}'    # firmware code
        D = lambda x: f'{bits(x,20,4):1d}{bits(x,16,4):1d}'     # firmware DD
        M = lambda x: f'{bits(x,24,4):02d}'                     # firmware MM
        Y = lambda x: f'{2016 + bits(x, 28, 4):4d}'             # firmware YYYY
        F, V = ('VME64', 'VME64X', 'DT', 'NIM'), {0x90:'M', 0x91:'N', 0x92:'P'}
        amcf = self.Reg32(0x108C)           # AMC Firmware Revision (ch0)
        rocf = self.Reg32(0x8124)           # ROC FPGA Firmware Revision
        fofa = self.Reg32(0xF034) & 0xF     # ROM Board Form Factor
        bove = self.Reg32(0xF030) & 0xFF    # ROM Board Version ('M' or 'N' or 'P')
        idb0 = self.Reg32(0xF03C) & 0xFF    # Configuration ROM Board ID BYTE 0
        idb1 = self.Reg32(0xF038) & 0xFF    # Configuration ROM Board ID BYTE 1
        boid = (idb1<<8) | idb0             # e.g. 5780
        snb0 = self.Reg32(0xF084) & 0xFF    # ROM Board Serial Number BYTE 0
        snb1 = self.Reg32(0xF080) & 0xFF    # ROM Board Serial Number BYTE 1
        sern = (snb1<<8) | snb0                # board serial number
        self.HV_POLA = [1,-1] if bove==0x90 else [-1,-1] if bove==0x91 else [1,1]
        hvps = self.GetInfoHV()                # could be '', 'SC' or 'SD'
        self.HV_Vmax = 2e+0  if hvps=='SD' else 2e+1
        self.HV_Vset = 1e-2  if hvps=='SD' else 1e-1
        self.HV_Iset = 1e-2  if hvps==''   else 5e-2
        self.BoardInfo['AMC Firmware' ] = f'{C(amcf)} - Build {Y(amcf)}.{M(amcf)}.{D(amcf)}'
        self.BoardInfo['ROC Firmware' ] = f'{C(rocf)} - Build {Y(rocf)}.{M(rocf)}.{D(rocf)}'
        self.BoardInfo['Board Model'  ] = f'{F[fofa]}{boid}{hvps}{V[bove]}'
        self.BoardInfo['Serial Number'] = f'{sern}'

Close the active CAENComm device handle.

Returns:

Type Description
bool | str

True on success, or an error description string.

Source code in caen/comm.py
90
91
92
93
94
95
96
97
98
99
def CloseLink(self) -> bool | str:
    """Close the active ``CAENComm`` device handle.

    Returns:
        ``True`` on success, or an error description string.
    """

    R = self.ErrorCode[self.clib.CAENComm_CloseDevice(self.handle)]
    print(f"Close Device: {R}")        
    return R

GetBoardInfo()

Read Configuration ROM and FPGA firmware registers to populate BoardInfo.

Also configures HVPS polarity signs (HV_POLA) and voltage/current step scaling factors (HV_Vmax, HV_Vset, HV_Iset).

Source code in caen/comm.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def GetBoardInfo(self):
    """Read Configuration ROM and FPGA firmware registers to populate ``BoardInfo``.

    Also configures HVPS polarity signs (``HV_POLA``) and voltage/current
    step scaling factors (``HV_Vmax``, ``HV_Vset``, ``HV_Iset``).
    """
    bits = lambda x, bit, size: (x>>bit)&((1<<size)-1)
    C = lambda x: f'{bits(x,8,8):03d}.{bits(x,0,8):<3d}'    # firmware code
    D = lambda x: f'{bits(x,20,4):1d}{bits(x,16,4):1d}'     # firmware DD
    M = lambda x: f'{bits(x,24,4):02d}'                     # firmware MM
    Y = lambda x: f'{2016 + bits(x, 28, 4):4d}'             # firmware YYYY
    F, V = ('VME64', 'VME64X', 'DT', 'NIM'), {0x90:'M', 0x91:'N', 0x92:'P'}
    amcf = self.Reg32(0x108C)           # AMC Firmware Revision (ch0)
    rocf = self.Reg32(0x8124)           # ROC FPGA Firmware Revision
    fofa = self.Reg32(0xF034) & 0xF     # ROM Board Form Factor
    bove = self.Reg32(0xF030) & 0xFF    # ROM Board Version ('M' or 'N' or 'P')
    idb0 = self.Reg32(0xF03C) & 0xFF    # Configuration ROM Board ID BYTE 0
    idb1 = self.Reg32(0xF038) & 0xFF    # Configuration ROM Board ID BYTE 1
    boid = (idb1<<8) | idb0             # e.g. 5780
    snb0 = self.Reg32(0xF084) & 0xFF    # ROM Board Serial Number BYTE 0
    snb1 = self.Reg32(0xF080) & 0xFF    # ROM Board Serial Number BYTE 1
    sern = (snb1<<8) | snb0                # board serial number
    self.HV_POLA = [1,-1] if bove==0x90 else [-1,-1] if bove==0x91 else [1,1]
    hvps = self.GetInfoHV()                # could be '', 'SC' or 'SD'
    self.HV_Vmax = 2e+0  if hvps=='SD' else 2e+1
    self.HV_Vset = 1e-2  if hvps=='SD' else 1e-1
    self.HV_Iset = 1e-2  if hvps==''   else 5e-2
    self.BoardInfo['AMC Firmware' ] = f'{C(amcf)} - Build {Y(amcf)}.{M(amcf)}.{D(amcf)}'
    self.BoardInfo['ROC Firmware' ] = f'{C(rocf)} - Build {Y(rocf)}.{M(rocf)}.{D(rocf)}'
    self.BoardInfo['Board Model'  ] = f'{F[fofa]}{boid}{hvps}{V[bove]}'
    self.BoardInfo['Serial Number'] = f'{sern}'

GetInfoHV()

Detect the installed High-Voltage Power Supply (HVPS) sub-module type.

Temporarily enters HVPS identification mode via register 0x1234 and restores the original register state in a finally block.

Returns:

Type Description
str

HVPS model suffix ('' for 5 kV, 'SC' for 4 kV, 'SD' for 0.5 kV, or '_' if unrecognized).

Source code in caen/comm.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def GetInfoHV(self) -> str:
    """Detect the installed High-Voltage Power Supply (HVPS) sub-module type.

    Temporarily enters HVPS identification mode via register ``0x1234`` and
    restores the original register state in a ``finally`` block.

    Returns:
        HVPS model suffix (``''`` for 5 kV, ``'SC'`` for 4 kV, ``'SD'`` for 0.5 kV,
            or ``'_'`` if unrecognized).
    """
    HV = (  '',       # 5kV 0.3mA
            'SC',     # 4kV   3mA 4W max
            'SD')     # 0.5kV 3mA
    n = None
    value = self.Reg32(0x1234)             # 0)
    try:
        self.Reg32(0x1234, value | 0x80)   # 1)
        sleep(0.1)                         # 2)
        version = self.Reg32(0x1238)       # 3)
        if version>=0x200:                 # 4)
            self.Reg32(0x1234, 0xB7)       # 5)
            sleep(0.1)                     # 6)
            n = self.Reg32(0x1240)         # 7)
    finally:
        self.Reg32(0x1234, value)          # 8)
        sleep(0.1)                         # 9)
    if n is not None and 0 <= n < len(HV):
        return HV[n]
    else:
        print('ask CAEN for support')
        return '_'

Open a communication link to the digitizer and query board metadata.

Parameters:

Name Type Description Default
LinkNum int

USB or optical link index.

0
LinkType str

Connection type ('USB' or 'Optical').

'USB'

Raises:

Type Description
ValueError

If CAENComm_OpenDevice2 returns a non-zero error code.

Source code in caen/comm.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def OpenLink(self, LinkNum=0, LinkType='USB'):
    """Open a communication link to the digitizer and query board metadata.

    Args:
        LinkNum (int): USB or optical link index.
        LinkType (str): Connection type (``'USB'`` or ``'Optical'``).

    Raises:
        ValueError: If ``CAENComm_OpenDevice2`` returns a non-zero error code.
    """
    LinkNum   = ct.byref(ct.c_uint32(LinkNum))
    LinkType  = self.LinkTypes.index(LinkType)
    R = self.clib.CAENComm_OpenDevice2(LinkType, LinkNum, 0, 0, ct.byref(self.handle))
    if R==0:
        self.GetBoardInfo()
    else:
        raise ValueError(self.ErrorCode[R])

ReadData()

Perform a Multi-Block Transfer (MBLT) readout into ReadOutBuffer.

Returns:

Type Description
int

Number of 32-bit words read from the digitizer memory.

Source code in caen/comm.py
119
120
121
122
123
124
125
126
127
128
129
130
    def ReadData(self) -> int:
        """Perform a Multi-Block Transfer (MBLT) readout into ``ReadOutBuffer``.

        Returns:
            Number of 32-bit words read from the digitizer memory.
        """
        nw = ct.c_int()
        R = self.clib.CAENComm_MBLTRead(self.handle, 0, self.ReadOutBuffer, self.BufferSize, ct.byref(nw))
#        print(f"Got {nw.value} samples!")
        if R!=0 and R!=-13:
            print(R, self.ErrorCode[R])
        return nw.value 

Reg32(addr, data=None)

Read or write a 32-bit hardware register.

Parameters:

Name Type Description Default
addr int

Register address (e.g., 0x8000).

required
data int | None

Value to write. If None, performs a 32-bit read.

None

Returns:

Type Description
int | str

Register value on read success, status code on write, or error string on failure.

Source code in caen/comm.py
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
def Reg32(self, addr, data=None) -> int | str:
    """Read or write a 32-bit hardware register.

    Args:
        addr (int): Register address (e.g., ``0x8000``).
        data (int | None): Value to write. If ``None``, performs a 32-bit read.

    Returns:
        Register value on read success, status code on write, or error string on failure.
    """
    if data is not None:
        return self.clib.CAENComm_Write32(self.handle, ct.c_uint32(addr), ct.c_uint32(data))
    else:
        data = ct.c_uint32()
        R = self.clib.CAENComm_Read32(self.handle, ct.c_uint32(addr), ct.byref(data))
        return data.value if R==0 else self.ErrorCode[R]

__init__(LinkNum=0, LinkType='USB')

Initialize board communication parameters and allocate readout buffer.

Parameters:

Name Type Description Default
LinkNum int

USB or optical link index. Defaults to 0.

0
LinkType str

Physical connection type ('USB' or 'Optical').

'USB'
Source code in caen/comm.py
51
52
53
54
55
56
57
58
59
60
61
62
63
def __init__(self, LinkNum=0, LinkType='USB'):
    """Initialize board communication parameters and allocate readout buffer.

    Args:
        LinkNum (int): USB or optical link index. Defaults to ``0``.
        LinkType (str): Physical connection type (``'USB'`` or ``'Optical'``).
    """
    self.LinkNum   = LinkNum
    self.LinkType  = LinkType
    self.handle    = ct.c_int(-1)
    self.ReadOutBuffer = (ct.c_uint32 * self.BufferSize)()
    self.BoardInfo = {}
    self.Reset = staticmethod(lambda: self.Reg32(0xEF24, 1))