SlsDetector.py 25 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
############################################################################
# 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
#
26
# description : Python common source for the PSI/SlsDetector and its commands.
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#                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
    return OrderedDict([(g(n), v) for n, v in zip(nl, vl)])


74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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)

#------------------------------------------------------------------
#    SlsDetector base device class
#------------------------------------------------------------------

92
93
94
95
96
class SlsDetector(PyTango.Device_4Impl):

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


97
98
    AttrNameRe = re.compile('_(?P<klass>[^_]+)__(?P<member>.+)')

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
#------------------------------------------------------------------
#    Device constructor
#------------------------------------------------------------------

    MilliVoltSuffix = '_mv'

    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()

129
130
131
        if self.initial_acq_params:
            self.perform_initial_acq(self.initial_acq_params)

132
133
134
135
        self.proc_finished = self.cam.getProcessingFinishedEvent()
        self.proc_finished.registerStatusCallback(_SlsDetectorControl)

        self.cam.setTolerateLostPackets(self.tolerate_lost_packets)
136
137
138
139
140
        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)
141
142
143
144
145
146
147
148
149
            self.cam.setPixelDepthCPUAffinityMap(aff_map)

    def init_list_attr(self):
        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):
150
        nb_modules = self.cam.getNbDetModules()
151
152
153
        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)
154
        self.dac_attr_idx_list = list(zip(attr_name_list, data_list))
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
        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)
176
        self.adc_attr_idx_list = list(zip(attr_name_list, data_list))
177
178
179
180
181
182
183
184
185
186
187
        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)

188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
    @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!")

203
204
205
206
    @Core.DEB_MEMBER_FUNCT
    def getAttrStringValueList(self, attr_name):
        return get_attr_string_value_list(self, attr_name)

207
208
    @Core.DEB_MEMBER_FUNCT
    def getDevAttr(self, name, obj=None):
209
210
211
212
213
        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)
214
215
216
217
218
219
        m = self.AttrNameRe.match(name)
        if m and (m.group('klass') != 'SlsDetector'):
            member = m.group('member')
            if member in ['PixelDepth']:
                return getattr(self, '_SlsDetector__' + member)
        obj = obj or self.cam
220
        return get_attr_4u(self, name, obj)
221
222
223
224
225
226
227
228
229
230
231
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
284
285
286
287

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

    @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 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]
288
        elif nb_val == self.cam.getNbDetModules():
289
290
291
292
293
294
295
296
297
298
            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):
299
        adc_name_list = list(zip(*self.adc_attr_idx_list))[0]
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        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
319
320
    def getNbBadFrames(self, recv_idx):
        nb_bad_frames = self.cam.getNbBadFrames(recv_idx);
321
322
323
324
        deb.Return("nb_bad_frames=%s" % nb_bad_frames)
        return nb_bad_frames

    @Core.DEB_MEMBER_FUNCT
325
326
    def getBadFrameList(self, recv_idx):
        bad_frame_list = self.cam.getBadFrameList(recv_idx);
327
328
329
330
        deb.Return("bad_frame_list=%s" % bad_frame_list)
        return bad_frame_list

    @Core.DEB_MEMBER_FUNCT
331
332
333
334
335
    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)
336
337
338
339
340
341
        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
342
343
344
345
346
    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)
347
348
349
350
351
352
        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
353
    def getPixelDepthCPUAffinityMapFromString(self, aff_str):
354
        CPUAffinity = SlsDetectorHw.CPUAffinity
355
356
        RecvCPUAffinity = SlsDetectorHw.RecvCPUAffinity
        NetDevRxQueueCPUAffinity = SlsDetectorHw.NetDevRxQueueCPUAffinity
357
358
        NetDevGroupCPUAffinity = SlsDetectorHw.NetDevGroupCPUAffinity
        GlobalCPUAffinity = SlsDetectorHw.GlobalCPUAffinity
359
360
361
362
363
364
365
366
367
368
        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():
369
            recv_aff, model_threads, lima, other, netdev_aff = aff_data
370
            global_aff = GlobalCPUAffinity()
371
            recv_list = []
372
            for listeners in recv_aff:
373
                recv = RecvCPUAffinity()
374
                recv.listeners = list(listeners)
375
                recv_list.append(recv)
376
            global_aff.recv = recv_list
377
            global_aff.model_threads = list(model_threads)
378
379
            global_aff.lima = lima
            global_aff.other = other
380
            ng_aff_list = []
381
            for name_list, queue_data in netdev_aff:
382
                ng_aff = NetDevGroupCPUAffinity()
383
384
385
386
387
388
389
390
                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
391
                ng_aff_list.append(ng_aff)
392
393
            global_aff.netdev = ng_aff_list
            aff_map[pixel_depth] = global_aff
394
395
396
        return aff_map

    @Core.DEB_MEMBER_FUNCT
397
398
399
400
401
402
403
    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)
404
405
        def aff_2_str(a):
            if type(a) in [tuple, list]:
406
                str_list = list(map(aff_2_str, a))
407
408
409
410
411
                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)
412
413
414
        for pixel_depth, global_aff in sorted(aff_map.items()):
            recv_list = []
            for r in global_aff.recv:
415
                recv_list.append(r.listeners)
416
            recv_str = aff_2_str(recv_list)
417
            model_threads_str = aff_2_str(global_aff.model_threads)
418
419
420
421
422
            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)
423
424
                queue_list = [('%d: %s)' % (q, aff_2_str((a.irq, 
                                                          a.processing))))
425
426
427
428
429
                              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)
430
431
432
433
            aff_str = '%d: (%s, %s, %s, %s, %s)' % (pixel_depth, recv_str,
                                                    model_threads_str,
                                                    lima_str, other_str,
                                                    netdev_grp_str)
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
            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)
459
460

    @Core.DEB_MEMBER_FUNCT
461
462
463
464
465
    def printGlobalAffinity(self, global_aff):
        def A(x):
            return hex(NumAffinity(x))
        for i, r in enumerate(global_aff.recv):
            s = "Recv[%d]:" % i
466
            s += " listeners=%s" % [A(x) for x in r.listeners]
467
            deb.Always('  ' + s)
468
469
        model_threads = global_aff.model_threads
        deb.Always('  ModelThreads=%s' % [A(x) for x in model_threads])
470
471
472
473
474
475
476
477
478
479
        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)
480
481
482
483

    @Core.DEB_MEMBER_FUNCT
    def read_pixel_depth_cpu_affinity_map(self, attr):
        aff_map = self.cam.getPixelDepthCPUAffinityMap()
484
485
486
        aff_str = self.getStringFromPixelDepthCPUAffinityMap(aff_map)
        deb.Return("aff_str=%s" % aff_str)
        attr.set_value(aff_str)
487
488
489

    @Core.DEB_MEMBER_FUNCT
    def write_pixel_depth_cpu_affinity_map(self, attr):
490
491
492
493
        aff_str = attr.get_write_value()
        deb.Param("aff_str=%s" % aff_str)
        aff_map = self.getPixelDepthCPUAffinityMapFromString(aff_str)
        self.printPixelDepthCPUAffinityMap(aff_map)
494
495
        self.cam.setPixelDepthCPUAffinityMap(aff_map)

496
497
498
    @Core.DEB_MEMBER_FUNCT
    def clearAllBuffers(self):
        self.cam.clearAllBuffers()
499

500
501
502
503
504

#------------------------------------------------------------------
#    SlsDetector base class
#------------------------------------------------------------------

505
506
507
508
509
510
511
512
class SlsDetectorClass(PyTango.DeviceClass):

    class_property_list = {}

    device_property_list = {
        'config_fname':
        [PyTango.DevString,
         "Path to the SlsDetector config file",[]],
513
514
515
        'full_config_fname':
        [PyTango.DevString,
         "In case of partial configuration, path to the full config file",[]],
516
517
518
519
        'initial_acq_params':
        [PyTango.DevString,
         "Initial acquisition parameters: "
         "acq_expo_time=0.01,acq_nb_frames=10,...", ""],
520
521
522
523
524
        'tolerate_lost_packets':
        [PyTango.DevBoolean,
         "Initial tolerance to lost packets", True],
        'pixel_depth_cpu_affinity_map':
        [PyTango.DevVarStringArray,
525
526
         "Default PixelDepthCPUAffinityMap as Python string(s) defining a dict: "
         "{<pixel_depth>: <global_affinity>}, being global_affinity a tuple: "
527
528
529
530
         "(<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: "
531
532
533
534
         "(<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", []],
535
536
537
538
539
540
541
542
543
544
545
546
547
        }

    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':
548
        [[PyTango.DevLong, "recv_idx(-1=all)"],
549
550
         [PyTango.DevLong, "Number of bad frames"]],
        'getBadFrameList':
551
        [[PyTango.DevLong, "recv_idx(-1=all)"],
552
553
         [PyTango.DevVarLongArray, "Bad frame list"]],
        'getStats':
554
        [[PyTango.DevString, "recv_idx(-1=all):stats_name"],
555
556
         [PyTango.DevVarDoubleArray, "Statistics: min, max, ave, std, n"]],
        'getStatsHistogram':
557
        [[PyTango.DevString, "recv_idx(-1=all):stats_name"],
558
         [PyTango.DevVarDoubleArray, "[[bin, count], ...]"]],
559
560
561
        'clearAllBuffers':
        [[PyTango.DevVoid, ""],
         [PyTango.DevVoid, ""]],
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
        }

    attr_list = {
        'config_fname':
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ]],
        'hostname_list':
        [[PyTango.DevString,
          PyTango.SPECTRUM,
          PyTango.READ, 64]],
        '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]],
        'max_frame_rate':
        [[PyTango.DevDouble,
          PyTango.SCALAR,
          PyTango.READ]],
        'tolerate_lost_packets':
        [[PyTango.DevBoolean,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        'pixel_depth_cpu_affinity_map':
602
603
604
        [[PyTango.DevString,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
605
606
607
608
609
610
611
612
613
614
615
        'stats_do_hist':
        [[PyTango.DevBoolean,
          PyTango.SCALAR,
          PyTango.READ_WRITE]],
        }

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


616
617
618
619
#----------------------------------------------------------------------------
# Deactivate modules in partial config
#----------------------------------------------------------------------------

620
621
622
623
624
625
626
def check_partial_config(config_name, full_config_name):
    if full_config_fname:
        p = Process(target=setup_partial_config,
                    args=(config_fname, full_config_fname))
        p.start()
        p.join()
    
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
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))
648
            cam.setModuleActive(i, False)
649
    print('Partial config: Done!')
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666


#----------------------------------------------------------------------------
# Plugin
#----------------------------------------------------------------------------
_SlsDetectorCam = None
_SlsDetectorHwInter = None
_SlsDetectorControl = None
    
def set_slsdetector_objs(cam, hwinter, control):
    global _SlsDetectorCam, _SlsDetectorHwInter, _SlsDetectorControl
    _SlsDetectorCam = cam
    _SlsDetectorHwInter = hwinter
    _SlsDetectorControl = control
    
def get_slsdetector_objs():
    return _SlsDetectorCam, _SlsDetectorHwInter, _SlsDetectorControl