Skip to content
biologic.py 68.2 KiB
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 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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 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 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 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 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 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 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 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 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 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 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
# -*- coding: utf-8 -*-
#
# This file is part of the bliss project
#
# Copyright (c) 2016 Beamline Control Unit, ESRF
# Distributed under the GNU LGPLv3. See LICENSE for more info.

'''
Biologic potentiostat module

Example::

    >>> from bliss.controllers.potentiostat.biologic import Potentiostat

    >>> p = Potentiostat('192.109.209.128')

    >>> # device information
    >>> print(p.info)
    DeviceInfo:
          DeviceType = DeviceType.SP50
             RAMsize = 32
                 CPU = 9200
    NumberOfChannels = ...

    >>> # list of plugged channels
    >>> p.get_channels_plugged()
    set([0])

    >>> # make sure channel 0 is installed
    >>> p.is_channel_plugged(0)
    True

    >>> # show current values of channel 0
    >>> print(p.get_current_values(0))
    CurrentValues:
        State = STOP
    MemFilled = 0
          Ewe = -0.007
            I = 0.0
         Freq = ...

    >>> # load OCV technique into channel 0
    >>> from bliss.controllers.potentiostat.biologic import VoltageRange
    >>> from bliss.controllers.potentiostat.biologic.techniques import OCV

    >>> ocv = OCV(OCV.Rest_time_T(0.1, 0),
    ...           OCV.Record_every_dE(0.1, 0),
    ...           OCV.Record_every_dT(0.01, 0),
    ...           OCV.E_Range(VoltageRange.AUTO))

    >>> self.p.load_technique(0, ocv)
'''

__all__ = ['PID', 'DeviceInfo', 'ChannelInfo', 'CurrentValues',
           'DataInfo', 'HardwareConf', 'TechniqueInfo',
           'ExperimentInfo', 'DeviceType', 'VMP3_SERIES', 'VMP4_SERIES',
           'SP_300_SERIES', 'Instrument', 'Technique', 'Parameter']

import os
import sys
import ctypes
import struct
import inspect
import logging
import functools
import collections
from enum import Enum
from ctypes import (c_int16, c_uint16, c_int32, c_uint32, c_int64, c_uint64,
    c_int8, c_uint8, c_float, c_double, c_bool, c_ubyte, c_char, c_char_p,
    Structure, byref, pointer, POINTER, create_string_buffer)

try:
    from collections import OrderedDict
except AttributeError:
    from ordereddict import OrderedDict

import numpy

from bliss.common.utils import API

c_uint8_p = POINTER(c_uint8)
c_uint16_p = POINTER(c_uint16)
c_uint32_p = POINTER(c_uint32)
c_uint64_p = POINTER(c_uint64)

c_int8_p = POINTER(c_int8)
c_int16_p = POINTER(c_int16)
c_int32_p = POINTER(c_int32)
c_int64_p = POINTER(c_int64)

_this_dir, _name = os.path.split(os.path.realpath(__file__))
_name, _ = os.path.splitext(_name)

_log = logging.getLogger(_name)

_is_32 = (8 * struct.calcsize('P')) == 32

_PY3 = sys.version_info[0] > 2

def NamedTuple(*args, **kwargs):
    r = collections.namedtuple(*args, **kwargs)
    def s(self):
        n = max(map(len, self._fields))
        T = '{{0: >{0}}} = {{1}}'.format(n)
        fields = '\n'.join([T.format(k, getattr(self, k)) for k in self._fields])
        return '{0}:\n{1}'.format(self.__class__.__name__, fields)
    r.__str__ = s
    return r

#: potentiostat identification
PID = NamedTuple('PID', 'ID dev_info url')

# Note on the need for following functions: We could have just done
# something like:
# eclib = LoadLibrary('eclib.dll')
# The problem that if the library is not present or we are not under
# windows, the generation of documentation would fail since the module
# could not be loaded. The functions allow for a *lazy* load and
# initialization of the biologic DLLs

def __get_lib(name):
    if not _is_32:
        name += '64'
    lib_path = os.path.join(_this_dir, name)
    return ctypes.WinDLL(lib_path)

def __init_eclib(c_eclib):
    # General functions

    c_eclib.BL_GetLibVersion.argtypes = [c_char_p, c_uint32_p]
    c_eclib.BL_GetLibVersion.restype = c_int32

    c_eclib.BL_GetVolumeSerialNumber.restype = c_uint32

    c_eclib.BL_GetErrorMsg.argtypes = [c_int32, c_char_p, c_uint32_p]
    c_eclib.BL_GetErrorMsg.restype = c_int32

    # Communication functions

    c_eclib.BL_Connect.argtypes = [c_char_p, c_uint8, c_int32_p, _DeviceInfo_p]
    c_eclib.BL_Connect.restype = c_int32

    c_eclib.BL_Disconnect.argtypes = [c_int32]
    c_eclib.BL_Disconnect.restype = c_int32

    c_eclib.BL_TestConnection.argtypes = [c_int32]
    c_eclib.BL_TestConnection.restype = c_int32

    c_eclib.BL_TestCommSpeed.argtypes = [c_int32, c_uint8, c_int32_p, c_int32_p]
    c_eclib.BL_TestCommSpeed.restype = c_int32

    c_eclib.BL_GetUSBdeviceinfos.argtypes = [c_uint32, c_char_p, c_uint32_p, c_char_p, c_uint32_p, c_char_p, c_uint32_p]
    c_eclib.BL_GetUSBdeviceinfos.restype = c_bool

    # Firmware functions

    c_eclib.BL_LoadFirmware.argtypes = [c_int32, c_uint8_p, c_int32_p, c_uint8,
                                        c_bool, c_bool, c_char_p, c_char_p]
    c_eclib.BL_LoadFirmware.restype = c_int32

    # Channel information functions

    c_eclib.BL_IsChannelPlugged.argtypes = [c_int32, c_uint8]
    c_eclib.BL_IsChannelPlugged.restype = c_bool

    c_eclib.BL_GetChannelsPlugged.argtypes = [c_int32, c_uint8_p, c_uint8]
    c_eclib.BL_GetChannelsPlugged.restype = c_int32

    c_eclib.BL_GetChannelInfos.argtypes = [c_int32, c_uint8, _ChannelInfo_p]
    c_eclib.BL_GetChannelInfos.restype = c_int32

    # Technique functions

    c_eclib.BL_DefineBoolParameter.argtypes = [c_char_p, c_bool, c_int32, _EccParam_p]
    c_eclib.BL_DefineBoolParameter.restype = c_int32

    c_eclib.BL_DefineSglParameter.argtypes = [c_char_p, c_float, c_int32, _EccParam_p]
    c_eclib.BL_DefineSglParameter.restype = c_int32

    c_eclib.BL_DefineIntParameter.argtypes = [c_char_p, c_int32, c_int32, _EccParam_p]
    c_eclib.BL_DefineIntParameter.restype = c_int32

    c_eclib.BL_LoadTechnique.argtypes = [c_int32, c_uint8, c_char_p, _EccParams, c_bool, c_bool, c_bool]
    c_eclib.BL_LoadTechnique.restype = c_int32
    # Start/stop functions

    # Data functions

    c_eclib.BL_GetCurrentValues.argtypes = [c_int32, c_uint8, _CurrentValues_p]
    c_eclib.BL_GetCurrentValues.restype = c_int32

    # Miscellaneous functions

    c_eclib.BL_SetExperimentInfos.argtypes = [c_int32, c_uint8, _ExperimentInfo]
    c_eclib.BL_SetExperimentInfos.restype = c_int32

__ECLIB = None
def eclib():
    global __ECLIB
    if not __ECLIB:
        __ECLIB = __get_lib('eclib')
        __init_eclib(__ECLIB)
    return __ECLIB

def __init_blfind(c_blfind):
    c_blfind.BL_FindEChemDev.argtypes = [c_char_p, c_uint32_p, c_uint32_p]
    c_blfind.BL_FindEChemDev.restype = c_int32

    c_blfind.BL_FindEChemEthDev.argtypes = [c_char_p, c_uint32_p, c_uint32_p]
    c_blfind.BL_FindEChemEthDev.restype = c_int32

    c_blfind.BL_FindEChemUsbDev.argtypes = [c_char_p, c_uint32_p, c_uint32_p]
    c_blfind.BL_FindEChemUsbDev.restype = c_int32

__BLFIND = None
def blfind():
    global __BLFIND
    if not __BLFIND:
        __BLFIND = __get_lib('blfind')
        __init_blfind(__BLFIND)
    return __BLFIND

def __struct_to_namedtuple_type(struct_class):
    # convert a ctypes.Structure to a namedtuple
    ret = NamedTuple(struct_class.__name__[1:], zip(*struct_class._fields_)[0])
    if _PY3:
        ret.__doc__ = s.__doc__
    return ret

def __struct_to_namedtuple(struct, ntuple_type=None):
    # convert a ctypes.Structure instance to a namedtuple instance. If
    # ntuple_type is None, it tries to find in globals a namedtuple with the
    # name of s[1:], if s starts with '_' otherwise throws ValueError 
    if ntuple_type is None:
        struct_name = struct.__class__.__name__
        if not struct_name.startswith('_'):
            raise ValueError('Cannot determine namedtuple name from structure ' \
                             'name {0}'.format(struct_name))
        ntuple_type = globals()[struct_name[1:]]
    kwargs = dict([(k, getattr(struct, k)) for k, _ in struct._fields_])
    return ntuple_type(**kwargs)

def __struct_to_dict(struct):
    fields = struct.__class__._fields_
    return dict([(name, getattr(struct, name)) for name, _ in fields])

def __namedtuple_to_struct(ntuple, struct_class=None):
    if struct_class is None:
        ntuple_name = ntuple.__class__.__name__
        if not ntuple_name.startswith('_'):
            raise ValueError('Cannot determine structure name from ' \
                             'namedtuple name {0}'.format(struct_name))
        struct_class = globals()['_' + ntuple_name]
    return struct_class(*ntuple)

def stringify_struct(k):
    M = max(map(len, [f[0] for f in k._fields_]))
    msg = '{{0: >{0}}} = {{1}}'.format(M)
    cname = k.__name__
    def s(self):
        f = [msg.format(name, getattr(self, name)) for name, _ in self._fields_]
        return '{0}:\n{1}'.format(cname, '\n'.join(f))
    k.__str__ = s
    return k

@stringify_struct
class _DeviceInfo(Structure):
    '''
    Information about the device that :func:`connect` connected to.
    '''
    _fields_ = [
        ('DeviceCode', c_int32),        # Device code
        ('RAMsize', c_int32),           # RAM size, in MBytes
        ('CPU', c_int32),               # Computer board cpu
        ('NumberOfChannels', c_int32),  # Number of channels connected
        ('NumberOfSlots', c_int32),     # Number of slots available
        ('FirmwareVersion', c_int32),   # Communication firmware version
        ('FirmwareDate_yyyy', c_int32), # Communication firmware date YYYY
        ('FirmwareDate_mm', c_int32),   # Communication firmware date MM
        ('FirmwareDate_dd', c_int32),   # Communication firmware date DD
        ('HTdisplayOn', c_int32),       # Allow hyper-terminal prints (true/false)
        ('NbOfConnectedPC', c_int32),   # Number of connected PC
    ]
_DeviceInfo_p = POINTER(_DeviceInfo)
DeviceInfo = __struct_to_namedtuple_type(_DeviceInfo)

@stringify_struct
class _ChannelInfo(Structure):
    '''
    Information about the channel. You can obtain them using
    :func:`get_channel_info`
    '''
    _fields_ = [
        ('Channel', c_int32),           # Channel (0..15)
        ('BoardVersion', c_int32),      # Board version
        ('BoardSerialNumber', c_int32), # Board serial number
        ('FirmwareCode', c_int32),      # Firmware loaded (see FirmwareCode)
        ('FirmwareVersion', c_int32),   # Firmware version
        ('XilinxVersion', c_int32),     # Xilinx version
        ('AmpCode', c_int32),           # Amplifier code (see AmplifierType)
        ('NbAmps', c_int32),            # Number of amplifiers
        ('Lcboard', c_int32),           # Low current board present (true/false)
        ('Zboard', c_int32),            # true if the channel has impedance measurement capability
        ('RESERVED', c_int32),          # not used
        ('RESERVED2', c_int32),         # not used
        ('MemSize', c_int32),           # Memory size (in bytes)
        ('MemFilled', c_int32),         # Memory filled (in bytes)
        ('State', c_int32),             # Channel State (see ChannelState)
        ('MaxIRange', c_int32),         # Maximum I range allowed (IntensityRange)
        ('MinIRange', c_int32),         # Minimum I range allowed (IntensityRange)
        ('MaxBandwidth', c_int32),      # Maximum bandwidth allowed (Bandwidth)
        ('NbOfTechniques', c_int32),    # Number of techniques loaded
    ]
_ChannelInfo_p = POINTER(_ChannelInfo)
ChannelInfo = __struct_to_namedtuple_type(_ChannelInfo)

@stringify_struct
class _CurrentValues(Structure):
    '''
    Information about the channel current values measurement.
    '''
    _fields_ = [
        ('State', c_int32),             # Channel state: see ChannelState
        ('MemFilled', c_int32),         # Memory filled (in Bytes)
        ('TimeBase', c_float),          # Time base (s)
        ('Ewe', c_float),               # Working electrode potential (V)
        ('EweRangeMin', c_float),       # Ewe min range (V)
        ('EweRangeMax', c_float),       # Ewe max range (V)
        ('Ece', c_float),               # Counter electrode potential (V)
        ('EceRangeMin', c_float),       # Ece min range (V)
        ('EceRangeMax', c_float),       # Ece max range (V)
        ('Eoverflow', c_int32),         # Potential overflow
        ('I', c_float),                 # Current value (A)
        ('IRange', c_int32),            # Current range (see IntensityRange)
        ('Ioverflow', c_int32),         # Current overflow
        ('ElapsedTime', c_float),       # Elapsed time (s)
        ('Freq', c_float),              # Frequency (Hz)
        ('Rcomp', c_float),             # R compensation (Ohm)
        ('Saturation', c_int32),        # E or/and I saturation
        ('OptErr', c_int32),            # Hardware option error code (see ErrorCodes, SP-300 series only)
        ('OptPos', c_int32),            # Index of the option generating the OptErr (SP-300 series only)
    ]
_CurrentValues_p = POINTER(_CurrentValues)
CurrentValues = __struct_to_namedtuple_type(_CurrentValues)

@stringify_struct
class _DataInfo(Structure):
    '''
    Holds metadata about the data you just received with :func:`get_data`
    '''
    _fields_ = [
        ('IRQskipped', c_int32),        # Number of IRQ skipped
        ('NbRows', c_int32),            # Number of rows into the data buffer, i.e.number of points saved in the data buffer
        ('NbCols', c_int32),            # Number of columns into the data buffer, i.e. number of variables defining a po('in the data buffer
        ('TechniqueIndex', c_int32),    # Index (0-based) of the technique who has generated the data. This field is only useful for linked techniques
        ('TechniqueID', c_int32),       # Identifier of the technique who has generated the data. Must be used to identify the data format into the data buffer (see TechniqueIdentifier )
        ('ProcessIndex', c_int32),      # Index (0-based) of the process of the technique who has generated the data. Must be used to identify the data format into the data buffer
        ('loop', c_int32),              # Loop number
        ('StartTime', c_double),        # Start time (s)
        ('MuxPad', c_int32),            # Active MP-MEA option pad number (SP-300 series only)
    ]
_DataInfo_p = POINTER(_DataInfo)
DataInfo = __struct_to_namedtuple_type(_DataInfo)

_DataBuffer = 1000 * c_uint32
_DataBuffer_p = POINTER(_DataBuffer)

@stringify_struct
class _EccParam(Structure):
    '''
    Defines an elementary technique parameter and is used by
    :func:`load_technique`
    '''
    _fields_ = [
        ('ParamStr', 64*c_char),        # (len=64) string who defines the parameter
                                        # label (see section 7. Techniques in PDF for
                                        # a complete description of parameters available
                                        # for each technique)
        ('ParamType', c_int32),         # Parameter type (see ParamType)
        ('ParamVal', c_int32),          # Parameter value. \warning Numerical value
        ('ParamIndex', c_int32),        # Parameter index (0-based), useful for multi-step parameters. Otherwise should be 0.
    ]
_EccParam_p = POINTER(_EccParam)

@stringify_struct
class _EccParams(Structure):
    '''
    Defines an array of elementary technique parameters and is used by
    :func:`load_technique`
    '''
    _fields_ = [
        ('len', c_int32),               # Length of the array pointed by pParams
        ('pParams', _EccParam_p),       # Pointer on the array of technique parameters (array of structure EccParam)
    ]
_EccParams_p = POINTER(_EccParams)

@stringify_struct
class _HardwareConf(Structure):
    '''
    Describes the channel electrode configuration.
    See :func:`get_hard_conf` and :func:`set_hard_conf`
    '''
    _fields_ = [
        ('Conn', c_int32),              # Electrode connection (see ElectrodeConn)
        ('Ground', c_int32),            # Instrument ground (see ElectrodeMode)
    ]
_HardwareConf_p = POINTER(_HardwareConf)
HardwareConf = __struct_to_namedtuple_type(_HardwareConf)

@stringify_struct
class _TechniqueInfo(Structure):
    '''Technique information'''
    _fields_ = [
        ('id', c_int32),                # technique id
        ('indx', c_int32),              # index of the technique
        ('nbParams', c_int32),          # number of parameters
        ('nbSettings', c_int32),        # number of hardware settings
        ('Params', _EccParam_p),        # pointer to the parameters
        ('HardSettings', _EccParam_p),  # pointer to the hardware settings
    ]
_TechniqueInfo_p = POINTER(_TechniqueInfo)
TechniqueInfo = __struct_to_namedtuple_type(_TechniqueInfo)

@stringify_struct
class _ExperimentInfo(Structure):
    '''Experiment informations'''
    _fields_ = [
        ('Group', c_int32),
        ('PCidentifier', c_int32),
        ('TimeHMS', c_int32),
        ('TimeYMD', c_int32),
        ('Filename', 256*c_char),
    ]
_ExperimentInfo_p = POINTER(_ExperimentInfo)
ExperimentInfo = __struct_to_namedtuple_type(_ExperimentInfo)

@API
class DeviceType(Enum):
    '''Device type'''
    VMP      = 0    #: VMP device
    VMP2     = 1    #: VMP2 device
    MPG      = 2    #: MPG device
    BISTAT   = 3    #: BISTAT device
    MCS_200  = 4    #: MCS-200 device
    VMP3     = 5    #: VMP3 device
    VSP      = 6    #: VSP device
    HCP803   = 7    #: HCP-803 device
    EPP400   = 8    #: EPP-400 device
    EPP4000  = 9    #: EPP-4000 device
    BISTAT2  = 10   #: BISTAT 2 device
    FCT150S  = 11   #: FCT-150S device
    VMP300   = 12   #: VMP-300 device
    SP50     = 13   #: SP-50 device
    SP150    = 14   #: SP-150 device
    FCT50S   = 15   #: FCT-50S device
    SP300    = 16   #: SP300 device
    CLB500   = 17   #: CLB-500 device
    HCP1005  = 18   #: HCP-1005 device
    CLB2000  = 19   #: CLB-2000 device
    VSP300   = 20   #: VSP-300 device
    SP200    = 21   #: SP-200 device
    MPG2     = 22   #: MPG2 device
    ND1      = 23   #: RESERVED
    ND2      = 24   #: RESERVED
    ND3      = 25   #: RESERVED
    ND4      = 26   #: RESERVED
    SP240    = 27   #: SP-240 device
    MPG205   = 28   #: MPG-205 (VMP3)
    MPG210   = 29   #: MPG-210 (VMP3)
    MPG220   = 30   #: MPG-220 (VMP3)
    MPG240   = 31   #: MPG-240 (VMP3)
    UNKNOWN  = 255  #: Unknown device

for i in range(32,255):
    setattr(DeviceType, 'UNSUPPORTED_{0}'.format(i), i)
        
VMP3_SERIES = set((DeviceType.VMP2, DeviceType.VMP3, DeviceType.BISTAT, 
                    DeviceType.VSP, DeviceType.SP50, DeviceType.SP150,
                    DeviceType.MPG2, DeviceType.HCP803))
VMP4_SERIES = set((DeviceType.SP200, DeviceType.SP240, DeviceType.SP300,
                   DeviceType.VSP300, DeviceType.VMP300))
SP_300_SERIES = set((DeviceType.SP200, DeviceType.SP240, DeviceType.SP300))


@API
class FirmwareCode(Enum):
    '''Firmware code'''
    NONE    = 0   #: No firmware loaded
    INTERPR = 1   #: Firmware for EC-Lab software
    UNKNOWN = 4   #: Unknown firmware loaded
    KERNEL  = 5   #: Firmware for the library
    INVALID = 8   #: Invalid firmware loaded
    ECAL    = 10  #: Firmware for calibration software

@API
class AmplifierType(Enum):
    '''Amplifier type'''
    VMP3_NONE        = 0   #: No amplifier VMP3 series
    VMP3_2A          = 1   #: Amplifier 2 A VMP3 series
    VMP3_1A          = 2   #: Amplifier 1 A VMP3 series
    VMP3_5A          = 3   #: Amplifier 5 A VMP3 series
    VMP3_10A         = 4   #: Amplifier 10 A VMP3 series
    VMP3_20A         = 5   #: Amplifier 20 A VMP3 series
    VMP3_HEUS        = 6   #: reserved VMP3 series
    VMP3_LC          = 7   #: Low current amplifier VMP3 series
    VMP3_80A         = 8   #: Amplifier 80 A VMP3 series
    VMP3_4AI         = 9   #: Amplifier 4 A VMP3 series
    VMP3_PAC         = 10  #: Fuel Cell Tester VMP3 series
    VMP3_4AI_VSP     = 11  #: Amplifier 4 A (VSP instrument) VMP3 series
    VMP3_LC_VSP      = 12  #: Low current amplifier (VSP instrument) VMP3 series
    VMP3_UNDEF       = 13  #: Undefined amplifier VMP3 series
    VMP3_MUIC        = 14  #: reserved VMP3 series
    VMP3_NONE_GIL    = 15  #: No amplifier VMP3 series
    VMP3_8AI         = 16  #: Amplifier 8 A VMP3 series
    VMP3_LB500       = 17  #: Amplifier LB500 VMP3 series
    VMP3_100A5V      = 18  #: Amplifier 100 A VMP3 series
    VMP3_LB2000      = 19  #: Amplifier LB2000 VMP3 series
    _1A48V           = 20  #: Amplifier 1A 48V SP-300 series
    _4A10V           = 21  #: Amplifier 4A 10V SP-300 series
    _5A_MPG2B        = 22  #: MPG-205 5A amplifier
    _10A_MPG2B       = 23  #: MPG-210 10A amplifier
    _20A_MPG2B       = 24  #: MPG-220 20A amplifier
    _40A_MPG2B       = 25  #: MPG-240 40A amplifier
    COIN_CELL_HOLDER = 26  #: coin cell holder
    VMP4_10A5V       = 27  #: VMP4 10A/5V amplifier (SP-300 internal amplifier)
    VMP4_2A30V       = 28  #: VMP4 2A/30V

@API
class IntensityRange(Enum):
    '''Intensity range'''
    _100pA   = 0   #: I range 100 pA SP-300 series
    _1nA     = 1   #: I range 1 nA VMP3 / SP-300 series
    _10nA    = 2   #: I range 10 nA VMP3 / SP-300 series
    _100nA   = 3   #: I range 100 nA VMP3 / SP-300 series
    _1uA     = 4   #: I range 1 uA VMP3 / SP-300 series
    _10uA    = 5   #: I range 10 uA VMP3 / SP-300 series
    _100uA   = 6   #: I range 100 uA VMP3 / SP-300 series
    _1mA     = 7   #: I range 1 mA VMP3 / SP-300 series
    _10mA    = 8   #: I range 10 mA VMP3 / SP-300 series
    _100mA   = 9   #: I range 100 mA VMP3 / SP-300 series
    _1A      = 10  #: I range 1 A VMP3 / SP-300 series
    BOOSTER  = 11  #: Booster VMP3 / SP-300 series
    AUTO     = 12  #: Auto range VMP3 / SP-300 series
    _10pA    = 13  #: IRANGE_100pA + Igain x10
    _1pA     = 14  #: IRANGE_100pA + Igain x100

@API
class OptionError(Enum):
    '''Option error codes'''
    NOERR           = 0    #: Option no error
    CHANGE          = 1    #: Option change
    _4A10V_ERR      = 100  #: Amplifier 4A10V error
    _4A10V_OVRTEMP  = 101  #: Amplifier 4A10V overload temperature
    _4A10V_BADPOW   = 102  #: Amplifier 4A10V invalid power
    _4A10V_POWFAIL  = 103  #: Amplifier 4A10V power fail
    _1A48V_ERR      = 200  #: Amplifier 1A48V error
    _1A48V_OVRTEMP  = 201  #: Amplifier 1A48V overload temperature
    _1A48V_BADPOW   = 202  #: Amplifier 1A48V invalid power
    _1A48V_POWFAIL  = 203  #: Amplifier 1A48V power fail
    _10A5V_ERR      = 300  #: Amplifier 10A5V error
    _10A5V_OVRTEMP  = 301  #: Amplifier 10A5V overload temperature
    _10A5V_BADPOW   = 302  #: Amplifier 10A5V invalid power
    _10A5V_POWFAIL  = 303  #: Amplifier 10A5V power fail

@API
class VoltageRange(Enum):
    '''Voltage range'''
    _2_5  = 0    # +/- 2.5 V
    _5    = 1    # +/- 5 V
    _10   = 2    # +/- 10 V
    AUTO = 3     # Auto range

@API
class Bandwidth(Enum):
    '''Channel bandwidth'''
    _1 = 1    # Bandwidth #1
    _2 = 2    # Bandwidth #2
    _3 = 3    # Bandwidth #3
    _4 = 4    # Bandwidth #4
    _5 = 5    # Bandwidth #5
    _6 = 6    # Bandwidth #6
    _7 = 7    # Bandwidth #7
    _8 = 8    # Bandwidth #8 (only with SP-300 series)
    _9 = 9    # Bandwidth #9 (only with SP-300 series)

@API
class Gain(Enum):
    '''E/I gain constants'''
    _1    = 0
    _10   = 1
    _100  = 2
    _1000 = 3

@API
class ElectrodeConn(Enum):
    '''Electrode connection'''
    STD = 0       # Standard connection
    CETOGRND = 1  # CE to ground connection
    WETOGRND = 2
    HV       = 3

@API
class ElectrodeMode(Enum):
    '''Electrode Ground mode'''
    GROUNDED = 0  # Grounded mode
    FLOATING = 1  # floating mode

@API
class FilterFreqCut(Enum):
    '''E/I filter constants'''
    NONE  = 0,
    _50KHZ = 1,
    _1KHZ  = 2,
    _5HZ   = 3,

@API
class TechniqueIdentifier(Enum):
    '''Technique ID'''
    NONE            = 0      # None
    OCV             = 100    # Open Circuit Voltage (Rest) identifier
    CA              = 101    # Chrono-amperometry identifier
    CP              = 102    # Chrono-potentiometry identifier
    CV              = 103    # Cyclic Voltammetry identifier
    PEIS            = 104    # Potentio Electrochemical Impedance Spectroscopy identifier
    POTPULSE        = 105    # (unused)
    GALPULSE        = 106    # (unused)
    GEIS            = 107    # Galvano Electrochemical Impedance Spectroscopy identifier
    STACKPEIS_SLAVE = 108    # Potentio Electrochemical Impedance Spectroscopy on stack identifier
    STACKPEIS       = 109    # Potentio Electrochemical Impedance Spectroscopy on stack identifier
    CPOWER          = 110    # Constant Power identifier
    CLOAD           = 111    # Constant Load identifier
    FCT             = 112    # (unused)
    SPEIS           = 113    # Staircase Potentio Electrochemical Impedance Spectroscopy identifier
    SGEIS           = 114    # Staircase Galvano Electrochemical Impedance Spectroscopy identifier
    STACKPDYN       = 115    # Potentio dynamic on stack identifier
    STACKPDYN_SLAVE = 116    # Potentio dynamic on stack identifier
    STACKGDYN       = 117    # Galvano dynamic on stack identifier
    STACKGEIS_SLAVE = 118    # Galvano Electrochemical Impedance Spectroscopy on stack identifier
    STACKGEIS       = 119    # Galvano Electrochemical Impedance Spectroscopy on stack identifier
    STACKGDYN_SLAVE = 120    # Galvano dynamic on stack identifier
    CPO             = 121    # (unused)
    CGA             = 122    # (unused)
    COKINE          = 123    # (unused)
    PDYN            = 124    # Potentio dynamic identifier
    GDYN            = 125    # Galvano dynamic identifier
    CVA             = 126    # Cyclic Voltammetry Advanced identifier
    DPV             = 127    # Differential Pulse Voltammetry identifier
    SWV             = 128    # Square Wave Voltammetry identifier
    NPV             = 129    # Normal Pulse Voltammetry identifier
    RNPV            = 130    # Reverse Normal Pulse Voltammetry identifier
    DNPV            = 131    # Differential Normal Pulse Voltammetry identifier
    DPA             = 132    # Differential Pulse Amperometry identifier
    EVT             = 133    # Ecorr vs. time identifier
    LP              = 134    # Linear Polarization identifier
    GC              = 135    # Generalized corrosion identifier
    CPP             = 136    # Cyclic Potentiodynamic Polarization identifier
    PDP             = 137    # Potentiodynamic Pitting identifier
    PSP             = 138    # Potentiostatic Pitting identifier
    ZRA             = 139    # Zero Resistance Ammeter identifier
    MIR             = 140    # Manual IR identifier
    PZIR            = 141    # IR Determination with Potentiostatic Impedance identifier
    GZIR            = 142    # IR Determination with Galvanostatic Impedance identifier
    LOOP            = 150    # Loop (used for linked techniques) identifier
    TO              = 151    # Trigger Out identifier
    TI              = 152    # Trigger In identifier
    TOS             = 153    # Trigger Set identifier
    CPLIMIT         = 155    # Chrono-potentiometry with limits identifier
    GDYNLIMIT       = 156    # Galvano dynamic with limits identifier
    CALIMIT         = 157    # Chrono-amperometry with limits identifier
    PDYNLIMIT       = 158    # Potentio dynamic with limits identifier
    LASV            = 159    # Large amplitude sinusoidal voltammetry
    MUXLOOP         = 160
    CVCA            = 161
    CVCA_SLAVE      = 162
    CPCA            = 163
    CPCA_SLAVE      = 164
    CACA            = 165
    CACA_SLAVE      = 166
    MP              = 167    # Modular Pulse
    CASG            = 169    # Constant amplitude sinusoidal micro galvano polarization
    CASP            = 170    # Constant amplitude sinusoidal micro potentio polarization
    VASP            = 171
    UCVANALOG       = 172

    OCVR            = 500
    CAR             = 501
    CPR             = 502

    ABS             = 1000
    FLUO            = 1001
    RABS            = 1002
    RFLUO           = 1003
    RDABS           = 1004
    DABS            = 1005
    ABSFLUO         = 1006
    RAFABS          = 1007
    RAFFLUO         = 1008

@API
class ChannelState(Enum):
    '''Channel State'''
    STOP  = 0    # Channel is stopped
    RUN   = 1    # Channel is running
    PAUSE = 2    # Channel is paused

@API
class ParameterType(Enum):
    '''Parameter type'''
    INT32   = 0    # Parameter type = int
    BOOLEAN = 1    # Parameter type = boolean
    SINGLE  = 2    # Parameter type = single

@API
class ECLibErrorCode(Enum):
    '''ECLib Error codes'''

    NOERROR = 0    # No Error

    # General error codes
    NOTCONNECTED          = -1    # no instrument connected
    CONNECTIONINPROGRESS  = -2    # connection in progress
    CHANNELNOTPLUGGED     = -3    # selected channel(s) unplugged
    INVALIDPARAMETERS     = -4    # invalid function parameters
    FILENOTEXISTS         = -5    # selected file does not exist
    FUNCTIONFAILED        = -6    # function failed
    NOCHANNELELECTED      = -7    # no channel selected
    INVALIDCONF           = -8    # invalid instrument configuration
    ECLAB_LOADED          = -9    # EC-Lab firmware loaded on the instrument
    LIBNOTCORRECTLYLOADED = -10   # library not correctly loaded in memory
    USBLIBRARYERROR       = -11   # USB library not correctly loaded in memory
    FUNCTIONINPROGRESS    = -12   # function of the library already in progress
    CHANNEL_RUNNING       = -13   # selected channel(s) already used
    DEVICE_NOTALLOWED     = -14   # device not allowed
    UPDATEPARAMETERS      = -15   # Invalid update function parameters

    # Instrument error codes
    VMEERROR        = -101      # internal instrument communication failed
    TOOMANYDATA     = -102      # too many data to transfer from the instrument (device error)
    RESPNOTPOSSIBLE = -103      # selected channel(s) unplugged (device error)
    RESPERROR       = -104      # instrument response error
    MSGSIZEERROR    = -105      # invalid message size

    # Communication error codes
    COMMFAILED         = -200    # communication failed with the instrument
    CONNECTIONFAILED   = -201    # cannot establish connection with the instrument
    WAITINGACK         = -202    # waiting for the instrument response
    INVALIDIPADDRESS   = -203    # invalid IP address
    ALLOCMEMFAILED     = -204    # cannot allocate memory in the instrument
    LOADFIRMWAREFAILED = -205    # cannot load firmware into selected channel(s)
    INCOMPATIBLESERVER = -206    # communication firmware not compatible with the library
    MAXCONNREACHED     = -207    # maximum number of allowed connections reached

    # Firmware error codes
    FIRMFILENOTEXISTS    = -300  # cannot find kernel.bin file
    FIRMFILEACCESSFAILED = -301  # cannot read kernel.bin file
    FIRMINVALIDFILE      = -302  # invalid kernel.bin file
    FIRMLOADINGFAILED    = -303  # cannot load kernel.bin on the selected channel(s)
    XILFILENOTEXISTS     = -304  # cannot find x100_01.txt file
    XILFILEACCESSFAILED  = -305  # cannot read x100_01.txt file
    XILINVALIDFILE       = -306  # invalid x100_01.txt file
    XILLOADINGFAILED     = -307  # cannot load x100_01.txt file on the selected channel(s)
    FIRMWARENOTLOADED    = -308  # no firmware loaded on the selected channel(s)
    FIRMWAREINCOMPATIBLE = -309  # loaded firmware not compatible with the library

    # Technique error codes
    ECCFILENOTEXISTS    = -400   # cannot find the selected ECC file
    INCOMPATIBLEECC     = -401   # ECC file not compatible with the channel firmware
    ECCFILECORRUPTED    = -402   # ECC file corrupted
    LOADTECHNIQUEFAILED = -403   # cannot load the ECC file
    DATACORRUPTED       = -404   # data returned by the instrument are corrupted
    MEMFULL             = -405   # cannot load techniques: full memory

@API
class BLFindErrorCode(Enum):
    '''BLFind Error codes'''

    NOERROR = 0    # No Error

    UNKNOWN           = -1  # unknown error
    INVALID_PARAMETER = -2  # invalid function parameters
    ACK_TIMEOUT       = -10 # instrument response timeout
    EXP_RUNNING       = -11 # experiment is running on instrument
    CMD_FAILED        = -12 # instrument do not execute command
    FIND_FAILED       = -20 # find failed
    SOCKET_WRITE      = -21 # cannot write the request of the descriptions of ethernet instruments
    SOCKET_READ       = -22 # cannot read descriptions of ethernet instrument
    CFG_MODIFY_FAILED = -30 # set TCP/IP parameters failed
    READ_PARAM_FAILED = -31 # deserialization of TCP/IP parameters failed
    EMPTY_PARAM       = -32 # not any TCP/IP parameters in serialization
    IP_FORMAT         = -33 # invalid format of IP address
    NM_FORMAT         = -34 # invalid format of netmask address
    GW_FORMAT         = -35 # invalid format of gateway address
    IP_NOT_FOUND      = -38 # instrument to modify not found
    IP_ALREADYEXIST   = -39 # new IP address in TCP/IP parameters already exists

@API
class ConnectionMode(Enum):
    '''Connection mode'''
    USB = 0
    ETH = 1

Instrument = NamedTuple('Instrument',
    ('connection_mode', 'address', 'gateway', 'netmask',
     'MAC', 'identifier', 'type', 'serial_number', 'name'))
Technique = NamedTuple('Technique', ('file_name', 'params'))
Parameter = NamedTuple('Parameter', ('name', 'value', 'index'))

@API
class MParameter(object):
    '''Meta parameter information'''
    def __init__(self, name, dtype, description='', len_range=(None, None),
                 value_range=(None, None)):
        self.name = name
        self.dtype = dtype
        self.description = description
        self.len_range = len_range
        self.value_range = value_range

    def __call__(self, value, index=0):
        return Parameter(self.name, self.dtype(value), index)

    def __getitem__(self, array):
        return [self(v, i) for i, v in enumerate(array)]

    def __repr__(self):
        return 'MParameter({0})'.format(self.name)

    def __str__(self):
        return 'MParameter({0})'.format(self.name)

@API
class MTechnique(object):
    '''Meta technique information.

       To create a new meta technique (not used often)::

       MYTECH = MTechnique(999, 'mytech',
                           MParameter('Rest_time_T', float, 'Rest duration (s)'),
                           MParameter('Record_every_dE', float, 'Record every dE (V)'),
                           MParameter('Record_every_dT', float, 'Record every dT (s)'),
                           summary="""my technique""",
                           description="""bla bla bla very good technique bla bla""")

       To create a new technique instance that can be loaded to the potentiostat do::

       p = Potentiostat('192.109.209.128')
       my_tech = MYTECH(MYTECH.Rest_time_T(0.1),
                        MYTECH.Record_every_dE(0.1),
                        MYTECH.Record_every_dT(0.1))

       p.load_technique(0, my_tech)
    '''

    HardwareParams = (
        MParameter('I_Range', IntensityRange, 'I range'),
        MParameter('E_Range', VoltageRange, 'Ewe range'),
        MParameter('Bandwidth', Bandwidth, 'Bandwith'),
        MParameter('tb', float, 'Time base (s)'),
    )

    def __init__(self, id, *meta_params, **kwargs):
        self.id = id
        meta_params = meta_params
        meta_params = self.HardwareParams + meta_params
        self.meta_params = OrderedDict((p.name, p) for p in meta_params)
        self.fname = kwargs.get('file_name', self.id.name.lower())
        self.summary = kwargs.pop('summary', '')
        self.description = kwargs.pop('description', '')
        self.handle_data = kwargs.pop('data_handler', None)

    @staticmethod
    def __params_iter(params):
        for param in params:
            if isinstance(param, Parameter):
                yield param
            else:
                for pparam in param:
                    yield pparam
    
    def __call__(self, *params):
        params = list(MTechnique.__params_iter(params))
        return Technique(self.fname, params)

    def __repr__(self):
        return 'MTechnique({0}, #{1})'.format(self.summary, self.id)

    def __str__(self):
        return 'MTechnique({0}, #{1})'.format(self.summary, self.id)

    def __getattr__(self, name):
        return self.meta_params[name]

# Exceptions -----------------------------------------------------------------

@API
class BiologicError(Exception):
    '''Base error class'''
    pass

@API
class BiologicErrorCode(BiologicError):
    '''Biologic error with error code'''
    def __init__(self, msg, error_code, *args):
        args = [msg] + list(args)
        super(BiologicError, self).__init__(*args)
        self.error_code = error_code

@API
class ECLibError(BiologicErrorCode):
    '''ECLib error with error code'''
    pass

@API
class BLFindError(BiologicErrorCode):
    '''BLFind error with error code'''
    pass

def __not_implemented(pid, *args, **kwargs):
    raise NotImplementedError

def __handle_params(f, args, kwargs):
    assert(len(args) == len(f.argtypes))
    f_args = []
    for arg_type, arg in zip(f.argtypes, args):
        # TODO
        f_args.append(arg)
    return f_args, kwargs

def __call_eclib(f, *args, **kwargs):
    '''
    calls the specified eclib function,
    transforming the result into an exception if necessary
    '''
    result = f(*args, **kwargs)
    result = ECLibErrorCode(result)
    if result != ECLibErrorCode.NOERROR:
        raise ECLibError(get_eclib_error_msg(result.value), result)
    return result

def __call_eclib_params(f, *args, **kwargs):
    '''
    calls the specified eclib function managing parameters in a default way,
    transforming the result into an exception if necessary
    '''
    f_args, f_kwargs = __handle_params(f, args, kwargs)
    __call_eclib(f, *f_args, **f_kwargs)

def __call_blfind(f, *args, **kwargs):
    result = f(*args, **kwargs)
    result = BLFindErrorCode(result)
    if result != BLFindErrorCode.NOERROR:
        raise BLFindError(get_blfind_error_msg(result.value), result)
    return result

def __unpack_str(msg, size):
    # some versions of the library have a bug which returns some strings
    # in the form: C\x00C\x00... where C is a valid character and \x00 is the null.
    # this function tries to overcome that problem
    size = size.value
    if msg[0] == '\x00':
        return ''
    if size < 2 or msg[1] != '\x00':
        return msg.value
    _log.warn('received strange response: %r...', msg[:10])
    return msg[0:size*2:2]

def _get_base_log_name(url):
    return 'Potentiostat({0})'.format(url)

def _get_log(url=None):
    if url is None:
        return _log
    return _log.getChild(_get_base_log_name(url))

def log_it(f=None, log_name='.', level=None, msg=None, args=None, kwargs=None):
    if f is None:
        return functools.partial(log_it, log_name=log_name, level=level,
                                 msg=msg, args=args, kwargs=kwargs)
    if msg is None:
        msg = f.__name__ + '()'
        args, kwargs = (), {}
    elif kwargs is None:
       kwargs = {}

    @functools.wraps(f)
    def wrap(pid, *a, **ka):
        if log_name == '.':
            log = _get_log(pid.url)
        else:
            log = _log.getChild(log_name)
        log.log(level, msg, *args, **kwargs)
        return f(pid, *a, **ka)
    return wrap

debug_it = functools.partial(log_it, level=logging.DEBUG)

## BL find -------------------------------------------------------------------

def __str_to_instruments(msg):
    instruments = []