# *****************************************************************************
# This program 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 2 of the License, or (at your option) any later
# version.
#
# This program 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, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Module authors:
#   Marek Bartkowiak <marek.bartkowiak@psi.ch>
# *****************************************************************************
# Example configuration
#IO('io_gain', 'serial:///dev/ttyUSB0?baudrate=115200')
#
#Mod('amplgain',
#    'frappy_psi.femtogsw.Gain',
#    'gainswitcher for FEMTO Amps',
#    io='io_gain',
#)
#
# Things to do:
# the gain is set in units= 'dB' and allowed values are 20 30 40 50 60
# Units are not allowed for IntRange

"""Gainswitch for FEMTO-Amplifier"""

from frappy.core import IntRange, HasIO, Parameter, StringIO, Writable


class IO(StringIO):
    end_of_line = '\n'
    default_settings = {'baudrate':115200}


class Gain(HasIO, Writable):
    ioClass = IO
    value = Parameter(datatype=IntRange(20,60,unit='dB'))
    target = Parameter(datatype=IntRange(20,60,unit='dB'))

    def read_value(self):
        return int(self.communicate('R'))

    def write_target(self, target):
        self.communicate(f'W{target:2d}')
        self.value = target

