SlsDetector.py 29.9 KB
Newer Older
1
2
3
4
5
6
7
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
############################################################################
# This file is part of LImA, a Library for Image Acquisition
#
# Copyright (C) : 2009-2011
# European Synchrotron Radiation Facility
# BP 220, Grenoble 38043
# FRANCE
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
############################################################################
#=============================================================================
#
# file :        SlsDetector.py
#
# description : Python source for the PSI/SlsDetector and its commands.
#                The class is derived from Device. It represents the
#                CORBA servant object which will be accessed from the
#                network. All commands which can be executed on the
#                SlsDetector are implemented in this file.
#
# project :     TANGO Device Server
#
# copyleft :    European Synchrotron Radiation Facility
#               BP 220, Grenoble 38043
#               FRANCE
#
#=============================================================================
#         (c) - Bliss - ESRF
#=============================================================================
#
42
import sys
43
44
45
46
import time, string
import numpy as np
import PyTango
from collections import OrderedDict
47
from functools import partial, reduce
48
49
from itertools import chain
from multiprocessing import Process
50
import re
51
52
53
54
55

from Lima import Core
from Lima import SlsDetector as SlsDetectorHw
from Lima.Server.AttrHelper import get_attr_4u, get_attr_string_value_list

56
57
NumAffinity = long if sys.version_info.major == 2 else int

58
def ConstListAttr(nl, vl=None, namespc=SlsDetectorHw.Defs):
59
60
61
62
63
64
65
66
67
68
69
    def g(x):
        n = ''
        was_cap = True
        for c in x:
            cap = c.isupper()
            sep = '_' if cap and not was_cap else ''
            n += sep + c.upper()
            was_cap = cap or not c.isalpha()
        return n

    if vl is None:
70
        vl = [getattr(namespc, n) for n in nl]
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    return OrderedDict([(g(n), v) for n, v in zip(nl, vl)])


class SlsDetector(PyTango.Device_4Impl):

    Core.DEB_CLASS(Core.DebModApplication, 'LimaSlsDetector')


#------------------------------------------------------------------
#    Device constructor
#------------------------------------------------------------------

    MilliVoltSuffix = '_mv'

85
86
87
88
89
    ModelAttrs = ['parallel_mode',
                  'high_voltage',
                  'clock_div',
                  'fixed_clock_div',
                  'threshold_energy',
90
                  'tx_frame_delay',
91
                  'fpga_frame_ptr_diff',
92
                  'img_proc_config',
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
    def __init__(self,*args) :
        PyTango.Device_4Impl.__init__(self,*args)
        self.init_device()

#------------------------------------------------------------------
#    Device destructor
#------------------------------------------------------------------
    def delete_device(self):
        pass

#------------------------------------------------------------------
#    Device initialization
#------------------------------------------------------------------
    @Core.DEB_MEMBER_FUNCT
    def init_device(self):
        self.set_state(PyTango.DevState.ON)
        self.get_device_properties(self.get_device_class())

        self.cam = _SlsDetectorCam
        self.model = self.cam.getModel()

        self.init_list_attr()
        self.init_dac_adc_attr()

119
120
121
        if self.initial_acq_params:
            self.perform_initial_acq(self.initial_acq_params)

122
123
124
        self.proc_finished = self.cam.getProcessingFinishedEvent()
        self.proc_finished.registerStatusCallback(_SlsDetectorControl)

125
126
127
128
129
130
131
        if self.high_voltage > 0:
            self.model.setHighVoltage(self.high_voltage)
        if self.fixed_clock_div > 0:
            self.model.setFixedClockDiv(self.fixed_clock_div)
        if self.threshold_energy > 0:
            self.model.setThresholdEnergy(self.threshold_energy)

132
        self.cam.setTolerateLostPackets(self.tolerate_lost_packets)
133
134
135
136
137
        aff_arr = self.pixel_depth_cpu_affinity_map
        if aff_arr:
            aff_str = ' '.join(aff_arr)
            aff_map = self.getPixelDepthCPUAffinityMapFromString(aff_str)
            self.printPixelDepthCPUAffinityMap(aff_map)
138
139
140
            self.cam.setPixelDepthCPUAffinityMap(aff_map)

    def init_list_attr(self):
141
        nl = ['FullSpeed', 'HalfSpeed', 'QuarterSpeed']
142
143
        self.__ClockDiv = ConstListAttr(nl)

144
        nl = ['NonParallel', 'Parallel']
145
        self.__ParallelMode = ConstListAttr(nl, namespc=SlsDetectorHw.Eiger)
146
147
148
149
150
151
152

        nl = ['PixelDepth4', 'PixelDepth8', 'PixelDepth16', 'PixelDepth32']
        bdl = map(lambda x: getattr(SlsDetectorHw, x), nl)
        self.__PixelDepth = OrderedDict([(str(bd), int(bd)) for bd in bdl])

    @Core.DEB_MEMBER_FUNCT
    def init_dac_adc_attr(self):
153
        nb_modules = self.cam.getNbDetModules()
154
155
156
        name_list, idx_list, milli_volt_list = self.model.getDACInfo()
        attr_name_list = map(lambda n: 'dac_' + n, name_list)
        data_list = zip(idx_list, milli_volt_list)
157
        self.dac_attr_idx_list = list(zip(attr_name_list, data_list))
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
        for name, data in self.dac_attr_idx_list:
            attr_data_dict = {
                'name': name, 
                'dtype': PyTango.DevLong,
                'dformat': PyTango.SPECTRUM,
                'max_dim_x': nb_modules,
                'fget': self.read_dac,
                'fset': self.write_dac,
            }
            attr_data = PyTango.AttrData.from_dict(attr_data_dict)
            self.add_attribute(attr_data)

            idx, has_mv = data
            if has_mv:
                attr_data_dict['name'] = name + self.MilliVoltSuffix
                attr_data = PyTango.AttrData.from_dict(attr_data_dict)
                self.add_attribute(attr_data)

        name_list, idx_list, factor_list, min_val_list = self.model.getADCInfo()
        attr_name_list = map(lambda n: 'adc_' + n, name_list)
        data_list = zip(idx_list, factor_list, min_val_list)
179
        self.adc_attr_idx_list = list(zip(attr_name_list, data_list))
180
181
182
183
184
185
186
187
188
189
190
        for name, data in self.adc_attr_idx_list:
            attr_data_dict = {
                'name': name, 
                'dtype': PyTango.DevDouble,
                'dformat': PyTango.SPECTRUM,
                'max_dim_x': nb_modules,
                'fget': self.read_adc,
            }
            attr_data = PyTango.AttrData.from_dict(attr_data_dict)
            self.add_attribute(attr_data)

191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
    @Core.DEB_MEMBER_FUNCT
    def perform_initial_acq(self, params):
        deb.Always("Performing initial setup acquisition: %s ..." % params)
        ct = _SlsDetectorControl
        acq = ct.acquisition()
        for x in params.split(','):
            n, v = x.split('=')
            attr_name = 'set' + ''.join([i.title() for i in n.split('_')])
            eval('acq.%s(%s)' % (attr_name, v))
        ct.prepareAcq()
        ct.startAcq()
        while ct.getStatus().AcquisitionStatus != Core.AcqReady:
            time.sleep(0.1)
        deb.Always("Done!")

206
207
208
209
210
211
212
213
214
215
    @Core.DEB_MEMBER_FUNCT
    def getAttrStringValueList(self, attr_name):
        return get_attr_string_value_list(self, attr_name)

    def __getattr__(self, name):
        if '_stats_' in name:
            stats_tok = name.split('_stats_')
            if stats_tok[1] in ['do_hist']:
                stats_name = '_'.join(stats_tok)
                return get_attr_4u(self, stats_name, SlsDetectorHw.SimpleStat)
216
217
218
219
220
        obj = self.cam
        for attr in self.ModelAttrs:
            if attr in name:
                obj = self.model
        return get_attr_4u(self, name, obj)
221
222
223
224
225
226

    @Core.DEB_MEMBER_FUNCT
    def read_config_fname(self, attr):
        deb.Return("config_fname=%s" % self.config_fname)
        attr.set_value(self.config_fname)

227
228
229
230
231
    @Core.DEB_MEMBER_FUNCT
    def read_apply_corrections(self, attr):
        deb.Return("apply_corrections=%s" % self.apply_corrections)
        attr.set_value(self.apply_corrections)

232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
    @Core.DEB_MEMBER_FUNCT
    def putCmd(self, cmd):
        deb.Param("cmd=%s" % cmd)
        self.cam.putCmd(cmd);

    @Core.DEB_MEMBER_FUNCT
    def getCmd(self, cmd):
        deb.Param("cmd=%s" % cmd)
        resp = self.cam.getCmd(cmd);
        deb.Return("resp=%s" % resp)
        return resp

    @Core.DEB_MEMBER_FUNCT
    def read_dac_name_list(self, attr):
        dac_name_list = [n for n, (i, m) in self.dac_attr_idx_list]
        deb.Return("dac_name_list=%s" % (dac_name_list,))
        attr.set_value(dac_name_list)

    @Core.DEB_MEMBER_FUNCT
    def read_dac_name_list_mv(self, attr):
        mv = self.MilliVoltSuffix
        dac_name_list = [n + mv for n, (i, m) in self.dac_attr_idx_list if m]
        deb.Return("dac_name_list=%s" % (dac_name_list,))
        attr.set_value(dac_name_list)

    @Core.DEB_MEMBER_FUNCT
    def get_dac_name_mv(self, dac_name):
        mv = self.MilliVoltSuffix
        is_mv = dac_name.endswith(mv)
        if is_mv:
            dac_name = dac_name[:-len(mv)]
        return dac_name, is_mv

    @Core.DEB_MEMBER_FUNCT
    def read_dac(self, attr):
        dac_name, milli_volt = self.get_dac_name_mv(attr.get_name())
        deb.Param("dac_name=%s, milli_volt=%s" % (dac_name, milli_volt))
        idx, has_mv = dict(self.dac_attr_idx_list)[dac_name]
        val_list = self.cam.getDACList(idx, milli_volt)
        deb.Return("val_list=%s" % val_list)
        attr.set_value(val_list)

    @Core.DEB_MEMBER_FUNCT
    def write_dac(self, attr):
        dac_name, milli_volt = self.get_dac_name_mv(attr.get_name())
        idx, has_mv = dict(self.dac_attr_idx_list)[dac_name]
        deb.Param("dac_name=%s, milli_volt=%s" % (dac_name, milli_volt))
        for i, val in self.get_write_mod_idx_val_list(attr):
            self.cam.setDAC(i, idx, val, milli_volt)

    @Core.DEB_MEMBER_FUNCT
    def read_all_trim_bits(self, attr):
284
        val_list = self.model.getAllTrimBitsList()
285
286
287
288
289
290
        deb.Return("val_list=%s" % val_list)
        attr.set_value(val_list)

    @Core.DEB_MEMBER_FUNCT
    def write_all_trim_bits(self, attr):
        for i, val in self.get_write_mod_idx_val_list(attr):
291
            self.model.setAllTrimBits(i, val)
292
293
294
295
296
297
298
299
300
301
302
303

    @Core.DEB_MEMBER_FUNCT
    def get_write_mod_idx_val_list(self, attr):
        attr_name = attr.get_name()
        val_list = attr.get_write_value()
        deb.Param("attr_name=%s, val_list=%s" % (attr_name, val_list))
        msg = None
        nb_val = len(val_list)
        if (val_list < 0).sum() == nb_val:
            msg = 'Invalid %s: %s' % (attr_name, val_list)
        elif nb_val == 1:
            mod_idx_list = [-1]
304
        elif nb_val == self.cam.getNbDetModules():
305
306
307
308
309
310
311
312
313
314
            mod_idx_list = range(nb_val)
        else:
            msg = 'Invalid %s length: %s' % (att_name, val_list)
        if msg:
            deb.Error(msg)
            raise ValueError(msg)
        return [(i, val) for i, val in zip(mod_idx_list, val_list) if val >= 0]

    @Core.DEB_MEMBER_FUNCT
    def read_adc_name_list(self, attr):
315
        adc_name_list = list(zip(*self.adc_attr_idx_list))[0]
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
        deb.Return("adc_name_list=%s" % (adc_name_list,))
        attr.set_value(adc_name_list)

    @Core.DEB_MEMBER_FUNCT
    def read_adc(self, attr):
        idx, factor, min_val = dict(self.adc_attr_idx_list)[attr.get_name()]
        val_list = self.cam.getADCList(idx)
        out_arr = np.array(val_list, 'float64') * factor + min_val
        deb.Return("out_arr=%s" % out_arr)
        attr.set_value(out_arr)

    @Core.DEB_MEMBER_FUNCT
    def read_max_frame_rate(self, attr):
        time_ranges = self.model.getTimeRanges()
        max_frame_rate = 1 / time_ranges.min_frame_period / 1e3;
        deb.Return("max_frame_rate=%s" % max_frame_rate)
        attr.set_value(max_frame_rate)

    @Core.DEB_MEMBER_FUNCT
335
336
    def getNbBadFrames(self, recv_idx):
        nb_bad_frames = self.cam.getNbBadFrames(recv_idx);
337
338
339
340
        deb.Return("nb_bad_frames=%s" % nb_bad_frames)
        return nb_bad_frames

    @Core.DEB_MEMBER_FUNCT
341
342
    def getBadFrameList(self, recv_idx):
        bad_frame_list = self.cam.getBadFrameList(recv_idx);
343
344
345
346
        deb.Return("bad_frame_list=%s" % bad_frame_list)
        return bad_frame_list

    @Core.DEB_MEMBER_FUNCT
347
348
349
350
351
    def getStats(self, recv_idx_stats_name):
        recv_idx_str, stats_name = recv_idx_stats_name.split(':')
        recv_idx = int(recv_idx_str)
        deb.Param("recv_idx=%s, stats_name=%s");
        stats = self.cam.getStats(recv_idx)
352
353
354
355
356
357
        stat = getattr(stats, stats_name)
        stat_data = [stat.min(), stat.max(), stat.ave(), stat.std(), stat.n()]
        deb.Return("stat_data=%s" % stat_data)
        return stat_data

    @Core.DEB_MEMBER_FUNCT
358
359
360
361
362
    def getStatsHistogram(self, recv_idx_stats_name):
        recv_idx_str, stats_name = recv_idx_stats_name.split(':')
        recv_idx = int(recv_idx_str)
        deb.Param("recv_idx=%s, stats_name=%s");
        stats = self.cam.getStats(recv_idx)
363
364
365
366
367
368
        stat = getattr(stats, stats_name)
        stat_data = np.array(stat.hist).flatten()
        deb.Return("stat_data=%s" % stat_data)
        return stat_data

    @Core.DEB_MEMBER_FUNCT
369
    def getPixelDepthCPUAffinityMapFromString(self, aff_str):
370
        CPUAffinity = SlsDetectorHw.CPUAffinity
371
372
        RecvCPUAffinity = SlsDetectorHw.RecvCPUAffinity
        NetDevRxQueueCPUAffinity = SlsDetectorHw.NetDevRxQueueCPUAffinity
373
374
        NetDevGroupCPUAffinity = SlsDetectorHw.NetDevGroupCPUAffinity
        GlobalCPUAffinity = SlsDetectorHw.GlobalCPUAffinity
375
376
377
378
379
380
381
382
383
384
        Mask = CPUAffinity
        def CPU(*x):
            if type(x[0]) in [tuple, list]:
                x = list(chain(*x))
            m = reduce(lambda a, b: a | b, map(lambda a: 1 << a, x))
            return Mask(m)
        aff_map_raw = eval(aff_str)
        self.expandPixelDepthRefs(aff_map_raw)
        aff_map = {}
        for pixel_depth, aff_data in aff_map_raw.items():
385
            recv_aff, model_threads, lima, other, netdev_aff = aff_data
386
            global_aff = GlobalCPUAffinity()
387
            recv_list = []
388
            for listeners in recv_aff:
389
                recv = RecvCPUAffinity()
390
                recv.listeners = list(listeners)
391
                recv_list.append(recv)
392
            global_aff.recv = recv_list
393
            global_aff.model_threads = list(model_threads)
394
395
            global_aff.lima = lima
            global_aff.other = other
396
            ng_aff_list = []
397
            for name_list, queue_data in netdev_aff:
398
                ng_aff = NetDevGroupCPUAffinity()
399
400
401
402
403
404
405
406
                ng_aff.name_list = name_list.split(',')
                queue_aff = {}
                for queue, (irq, proc) in queue_data.items():
                    ng_aff_queue = NetDevRxQueueCPUAffinity()
                    ng_aff_queue.irq = irq
                    ng_aff_queue.processing = proc
                    queue_aff[queue] = ng_aff_queue
                ng_aff.queue_affinity = queue_aff
407
                ng_aff_list.append(ng_aff)
408
409
            global_aff.netdev = ng_aff_list
            aff_map[pixel_depth] = global_aff
410
411
412
        return aff_map

    @Core.DEB_MEMBER_FUNCT
413
414
415
416
417
418
419
    def getStringFromPixelDepthCPUAffinityMap(self, aff_map, use_cpu=True):
        pixel_depth_aff_list = []
        def cpu_str(a):
            cpu_list = [str(i) for i in range(128) if NumAffinity(a) & (1 << i)]
            return 'CPU(%s)' % ', '.join(cpu_list)
        def mask_str(a):
            return 'Mask(0x%x)' % NumAffinity(a)
420
421
        def aff_2_str(a):
            if type(a) in [tuple, list]:
422
                str_list = list(map(aff_2_str, a))
423
424
425
426
427
                if len(str_list) == 1:
                    str_list.append('')
                return '(%s)' % ', '.join(str_list)
            f = cpu_str if use_cpu else mask_str
            return f(a)
428
429
430
        for pixel_depth, global_aff in sorted(aff_map.items()):
            recv_list = []
            for r in global_aff.recv:
431
                recv_list.append(r.listeners)
432
            recv_str = aff_2_str(recv_list)
433
            model_threads_str = aff_2_str(global_aff.model_threads)
434
435
436
437
438
            lima_str = aff_2_str(global_aff.lima)
            other_str = aff_2_str(global_aff.other)
            netdev_grp_list = []
            for netdev_grp in global_aff.netdev:
                name_str = ','.join(netdev_grp.name_list)
439
440
                queue_list = [('%d: %s)' % (q, aff_2_str((a.irq, 
                                                          a.processing))))
441
442
443
444
445
                              for q, a in netdev_grp.queue_affinity.items()]
                queue_str = ','.join(queue_list)
                netdev_str = '"%s": {%s}' % (name_str, queue_str)
                netdev_grp_list.append(netdev_str)
            netdev_grp_str = '(%s)' % ', '.join(netdev_grp_list)
446
447
448
449
            aff_str = '%d: (%s, %s, %s, %s, %s)' % (pixel_depth, recv_str,
                                                    model_threads_str,
                                                    lima_str, other_str,
                                                    netdev_grp_str)
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
            pixel_depth_aff_list.append(aff_str)
        return '{%s}' % ', '.join(pixel_depth_aff_list)

    @Core.DEB_MEMBER_FUNCT
    def expandPixelDepthRefs(self, aff_map):
        for k, v in aff_map.items():
            if type(v) != str:
                continue
            re_str = '^@(%s)$' % '|'.join(self.__PixelDepth.keys())
            re_obj = re.compile(re_str)
            m = re_obj.match(v)
            if not m:
                err = 'Invalid pixel_depth_cpu_affinity_map entry: %s' % v
                raise ValueError(err)
            o = int(m.group(1))
            v = aff_map[o]
            if type(v) == str:
                raise ValueError('Invalid reference to pixel depth %d' % o)
            aff_map[k] = v

    @Core.DEB_MEMBER_FUNCT
    def printPixelDepthCPUAffinityMap(self, aff_map):
        for pixel_depth, global_aff in sorted(aff_map.items()):
            deb.Always('PixelDepth: %d' % pixel_depth)
            self.printGlobalAffinity(global_aff)
475
476

    @Core.DEB_MEMBER_FUNCT
477
478
479
480
481
    def printGlobalAffinity(self, global_aff):
        def A(x):
            return hex(NumAffinity(x))
        for i, r in enumerate(global_aff.recv):
            s = "Recv[%d]:" % i
482
            s += " listeners=%s" % [A(x) for x in r.listeners]
483
            deb.Always('  ' + s)
484
485
        model_threads = global_aff.model_threads
        deb.Always('  ModelThreads=%s' % [A(x) for x in model_threads])
486
487
488
489
490
491
492
493
494
495
        lima, other = global_aff.lima, global_aff.other
        deb.Always('  Lima=%s, Other=%s' % (A(lima), A(other)))
        for netdev_grp in global_aff.netdev:
            s = "NetDevGroup[%s]: {" % ','.join(netdev_grp.name_list)
            l = []
            for queue, queue_aff in netdev_grp.queue_affinity.items():
                l.append('%d: (%s, %s)' % (queue, A(queue_aff.irq), 
                                           A(queue_aff.processing)))
            s += ','.join(l) + "}"
            deb.Always('  ' + s)
496
497
498
499

    @Core.DEB_MEMBER_FUNCT
    def read_pixel_depth_cpu_affinity_map(self, attr):
        aff_map = self.cam.getPixelDepthCPUAffinityMap()
500
501
502
        aff_str = self.getStringFromPixelDepthCPUAffinityMap(aff_map)
        deb.Return("aff_str=%s" % aff_str)
        attr.set_value(aff_str)
503
504
505

    @Core.DEB_MEMBER_FUNCT
    def write_pixel_depth_cpu_affinity_map(self, attr):
506
507
508
509
        aff_str = attr.get_write_value()
        deb.Param("aff_str=%s" % aff_str)
        aff_map = self.getPixelDepthCPUAffinityMapFromString(aff_str)
        self.printPixelDepthCPUAffinityMap(aff_map)
510
511
        self.cam.setPixelDepthCPUAffinityMap(aff_map)

512
513
514
    @Core.DEB_MEMBER_FUNCT
    def read_jungfrau_gain_map(self, attr):
        jungfrau = _SlsDetectorJungfrau
515
516
        gain_data, adc_data, frame = jungfrau.readGainADCMaps(-1)
        deb.Always("frame=%s" % frame)
517
518
519
520
521
        attr.set_value(gain_data.buffer)

    @Core.DEB_MEMBER_FUNCT
    def read_jungfrau_adc_map(self, attr):
        jungfrau = _SlsDetectorJungfrau
522
523
        gain_data, adc_data, frame = jungfrau.readGainADCMaps(-1)
        deb.Always("frame=%s" % frame)
524
525
        attr.set_value(adc_data.buffer)

526
527
528
    @Core.DEB_MEMBER_FUNCT
    def clearAllBuffers(self):
        self.cam.clearAllBuffers()
529
530
531
532
533
534
535
536
537

class SlsDetectorClass(PyTango.DeviceClass):

    class_property_list = {}

    device_property_list = {
        'config_fname':
        [PyTango.DevString,
         "Path to the SlsDetector config file",[]],
538
539
540
        'full_config_fname':
        [PyTango.DevString,
         "In case of partial configuration, path to the full config file",[]],
541
542
543
544
        'initial_acq_params':
        [PyTango.DevString,
         "Initial acquisition parameters: "
         "acq_expo_time=0.01,acq_nb_frames=10,...", ""],
545
546
547
548
549
550
551
552
553
554
        'high_voltage':
        [PyTango.DevShort,
         "Initial detector high voltage (V) "
         "(set to 150 if already tested)", 0],
        'fixed_clock_div':
        [PyTango.DevShort,
         "Initial detector fixed-clock-div (0, 1)", 0],
        'threshold_energy':
        [PyTango.DevLong,
         "Initial detector threshold energy (eV)", 0],
555
556
557
        'tolerate_lost_packets':
        [PyTango.DevBoolean,
         "Initial tolerance to lost packets", True],
558
559
560
        'apply_corrections':
        [PyTango.DevBoolean,
         "Apply frame corrections", True],
561
562
        'pixel_depth_cpu_affinity_map':
        [PyTango.DevVarStringArray,
563
564
         "Default PixelDepthCPUAffinityMap as Python string(s) defining a dict: "
         "{<pixel_depth>: <global_affinity>}, being global_affinity a tuple: "
565
566
567
568
         "(<recv_list>, <model_threads>, <lima>, <other>, <netdev_grp_list>), "
         "where recv_list is a list of tuples of listeners affinities, "
         "model_threads a tuple of affinities, lima and other are affinities, "
         "and netdev_grp_list is a list of tuples in the form: "
569
570
571
572
         "(<comma_separated_netdev_name_list>, <rx_queue_affinity_map>), the "
         "latter in the form of: {<queue>: (<irq>, <processing>)}. "
         "Each affinity can be expressed by one of the functions: Mask(mask) "
         "or CPU(<cpu1>[, ..., <cpuN>]) for independent CPU enumeration", []],
573
574
575
576
577
578
579
580
581
582
583
584
585
        }

    cmd_list = {
        'getAttrStringValueList':
        [[PyTango.DevString, "Attribute name"],
         [PyTango.DevVarStringArray, "Authorized String value list"]],
        'putCmd':
        [[PyTango.DevString, "SlsDetector command"],
         [PyTango.DevVoid, ""]],
        'getCmd':
        [[PyTango.DevString, "SlsDetector command"],
         [PyTango.DevString, "SlsDetector response"]],
        'getNbBadFrames':
586
        [[PyTango.DevLong, "recv_idx(-1=all)"],
587
588
         [PyTango.DevLong, "Number of bad frames"]],
        'getBadFrameList':
589
        [[PyTango.DevLong, "recv_idx(-1=all)"],
590
591
         [PyTango.DevVarLongArray, "Bad frame list"]],
        'getStats':
592
        [[PyTango.DevString, "recv_idx(-1=all):stats_name"],
593
594
         [PyTango.DevVarDoubleArray, "Statistics: min, max, ave, std, n"]],
        'getStatsHistogram':
595
        [[PyTango.DevString, "recv_idx(-1=all):stats_name"],
596
         [PyTango.DevVarDoubleArray, "[[bin, count], ...]"]],
597
598
599
        'clearAllBuffers':
        [[PyTango.DevVoid, ""],
         [PyTango.DevVoid, ""]],
600
601
602
603
604
605
606
607
608
609
610
        }

    attr_list = {
        'config_fname':
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ]],
        'hostname_list':
        [[PyTango.DevString,
          PyTango.SPECTRUM,
          PyTango.READ, 64]],
611
612
613
614
        'apply_corrections':
        [[PyTango.DevBoolean,
          PyTango.SCALAR,
          PyTango.READ]],
615
616
617
618
        'img_proc_config':
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
        'dac_name_list':
        [[PyTango.DevString,
          PyTango.SPECTRUM,
          PyTango.READ, 64]],
        'dac_name_list_mv':
        [[PyTango.DevString,
          PyTango.SPECTRUM,
          PyTango.READ, 64]],
        'adc_name_list':
        [[PyTango.DevString,
          PyTango.SPECTRUM,
          PyTango.READ, 64]],
        'pixel_depth':
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'raw_mode':
        [[PyTango.DevBoolean,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'threshold_energy':
        [[PyTango.DevLong,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'all_trim_bits':
        [[PyTango.DevLong,
          PyTango.SPECTRUM,
          PyTango.READ_WRITE, 64]],
647
648
649
650
        'high_voltage':
        [[PyTango.DevLong,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
651
652
653
654
        'clock_div':
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
655
656
657
658
659
        'fixed_clock_div':
        [[PyTango.DevBoolean,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'parallel_mode':
660
661
662
663
664
665
666
667
668
669
670
671
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'max_frame_rate':
        [[PyTango.DevDouble,
          PyTango.SCALAR,
          PyTango.READ]],
        'tolerate_lost_packets':
        [[PyTango.DevBoolean,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'pixel_depth_cpu_affinity_map':
672
673
674
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
675
676
677
678
        'stats_do_hist':
        [[PyTango.DevBoolean,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
679
        'skip_frame_freq':
680
681
682
683
        [[PyTango.DevLong,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'tx_frame_delay':
684
685
686
        [[PyTango.DevLong,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
687
688
689
690
        'fpga_frame_ptr_diff':
        [[PyTango.DevULong,
          PyTango.SPECTRUM,
          PyTango.READ, 64]],
691
692
693
694
695
696
697
698
        'jungfrau_gain_map':
        [[PyTango.DevUChar,
          PyTango.IMAGE,
          PyTango.READ, 8192, 8192]],
        'jungfrau_adc_map':
        [[PyTango.DevUShort,
          PyTango.IMAGE,
          PyTango.READ, 8192, 8192]],
699
700
701
702
703
704
705
706
707
708
709
710
711
        }

    def __init__(self,name) :
        PyTango.DeviceClass.__init__(self,name)
        self.set_type(name)


#----------------------------------------------------------------------------
# Plugin
#----------------------------------------------------------------------------
_SlsDetectorCam = None
_SlsDetectorHwInter = None
_SlsDetectorEiger = None
712
_SlsDetectorJungfrau = None
713
_SlsDetectorCorrection = None
714
_SlsDetectorImgProc = None
715
716
_SlsDetectorControl = None

717
718
def get_control(config_fname, full_config_fname=None, apply_corrections=None,
                **keys) :
719
720
    global _SlsDetectorCam, _SlsDetectorHwInter
    global _SlsDetectorEiger, _SlsDetectorJungfrau
721
722
    global _SlsDetectorCorrection, _SlsDetectorImgProc
    global _SlsDetectorControl
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739

    def to_bool(x, default_val=False):
        if x is None:
            return default_val
        elif type(x) is str:
            x = x.lower()
            if x == 'true':
                return True
            elif x == 'false':
                return False
            else:
                return bool(int(x))
        else:
            return bool(x)

    apply_corrections = to_bool(apply_corrections, True)

740
    if _SlsDetectorControl is None:
741
742
743
744
745
746
        if full_config_fname:
            p = Process(target=setup_partial_config,
                        args=(config_fname, full_config_fname))
            p.start()
            p.join()

747
748
        det_id = 0
        _SlsDetectorCam = SlsDetectorHw.Camera(config_fname, det_id)
749
750
751
752
753
        det_type = _SlsDetectorCam.getType()
        if det_type == SlsDetectorHw.EigerDet:
            for i, n in enumerate(_SlsDetectorCam.getHostnameList()):
                print('Enabling: %s (%d)' % (n, i))
                _SlsDetectorCam.setModuleActive(i, True)
754

755
        _SlsDetectorHwInter = SlsDetectorHw.Interface(_SlsDetectorCam)
756
        if det_type == SlsDetectorHw.EigerDet:
757
            _SlsDetectorEiger = SlsDetectorHw.Eiger(_SlsDetectorCam)
758
759
            if apply_corrections:
                _SlsDetectorCorrection = _SlsDetectorEiger.createCorrectionTask()
760
761
        elif det_type == SlsDetectorHw.JungfrauDet:
            _SlsDetectorJungfrau = SlsDetectorHw.Jungfrau(_SlsDetectorCam)
762
            _SlsDetectorImgProc = _SlsDetectorJungfrau.createImgProcTask()
763
764
765
766
767
768
        else:
            raise ValueError("Unknown detector type: %s" %
                             _SlsDetectorCam.getType())
        _SlsDetectorControl = Core.CtControl(_SlsDetectorHwInter)
        if _SlsDetectorCorrection:
            _SlsDetectorControl.setReconstructionTask(_SlsDetectorCorrection)
769
770
771
772
773
        if _SlsDetectorImgProc:
            ext_op_mgr = _SlsDetectorControl.externalOperation()
            alias = 'SlsDetectorImgProc'
            soft_op = ext_op_mgr.addOp(Core.USER_SINK_TASK, alias, 0)
            soft_op.setSinkTask(_SlsDetectorImgProc)
774
775
776
777
    return _SlsDetectorControl 

def get_tango_specific_class_n_device():
    return SlsDetectorClass, SlsDetector
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804


#----------------------------------------------------------------------------
# Deactivate modules in partial config
#----------------------------------------------------------------------------

def setup_partial_config(config_fname, full_config_fname):
    import re

    cam = SlsDetectorHw.Camera(full_config_fname)
    full_hostname_list = cam.getHostnameList()
    print('Full config: %s' % ','.join(full_hostname_list))
    host_re_str = '([A-Za-z0-9]+)+?'
    host_re_obj = re.compile(host_re_str)
    re_obj = re.compile('^[ \\t]*hostname[ \\t]+(%s[^# ]+)' % host_re_str)
    partial_hostname_list = []
    with open(config_fname) as f:
        for l in f:
            m = re_obj.match(l)
            if m:
                s = m.groups()[0]
                partial_hostname_list = host_re_obj.findall(s)
                break
    print('Partial config: %s' % ','.join(partial_hostname_list))
    for i, n in enumerate(full_hostname_list):
        if n not in partial_hostname_list:
            print('Disabling: %s (%d)' % (n, i))
805
            cam.setModuleActive(i, False)
806
    print('Partial config: Done!')