import logging; logging.basicConfig(level=logging.DEBUG)
import time

import mr_box_peripheral_board as mrbox
import serial
reload(mrbox)

# Try to connect to MR-Box control board.
retry_count = 2
for i in xrange(retry_count):
    try:
        proxy.close()
    except NameError:
        pass
    try:
        proxy = mrbox.SerialProxy(baudrate=57600, settling_time_s=2.5)
        break
    except serial.SerialException:
        time.sleep(1)
else:
    raise IOError('Could not connect to MR-Box control board.')
    
proxy._timeout_s = 20

"""
Explanation: Table of Contents
<p><div class="lev1 toc-item"><a href="#Z-Stage" data-toc-modified-id="Z-Stage-1"><span class="toc-item-num">1&nbsp;&nbsp;</span>Z-Stage</a></div><div class="lev1 toc-item"><a href="#Pump" data-toc-modified-id="Pump-2"><span class="toc-item-num">2&nbsp;&nbsp;</span>Pump</a></div><div class="lev1 toc-item"><a href="#PMT" data-toc-modified-id="PMT-3"><span class="toc-item-num">3&nbsp;&nbsp;</span>PMT</a></div><div class="lev1 toc-item"><a href="#MAX11210-ADC" data-toc-modified-id="MAX11210-ADC-4"><span class="toc-item-num">4&nbsp;&nbsp;</span>MAX11210 ADC</a></div>
End of explanation
"""


from mr_box_peripheral_board import zstage_ui
reload(zstage_ui)

zstage_ui_ = zstage_ui.ZStageUI(proxy)
# Display user interface for z-stage.
zstage_ui_.widget

"""
Explanation: Z-Stage
End of explanation
"""


from mr_box_peripheral_board import pump_ui
reload(pump_ui)

pump_ui_ = pump_ui.PumpUI(proxy)
pump_ui_.widget


"""
Explanation: Pump
End of explanation
"""


import si_prefix as si

from mr_box_peripheral_board import pmt_ui
reload(pmt_ui)

pmt_ui_ = pmt_ui.PmtUI(proxy)
pmt_ui_.widget

"""
Explanation: PMT
End of explanation
"""


from mr_box_peripheral_board import max11210_adc_ui
reload(max11210_adc_ui)

# max11210_adc_ui_ = max11210_adc_ui.Max11210AdcUI(proxy)
# max11210_adc_ui_.widget

import ipywidgets as ipw

INPUT_RANGE_UNIPOLAR = 1
INPUT_RANGE_BIPOLAR = 2
CLOCK_SOURCE_EXTERNAL = 1
CLOCK_SOURCE_INTERNAL = 2
FORMAT_OFFSET = 1
FORMAT_TWOS_COMPLEMENT = 2
CONVERSION_MODE_SINGLE = 1
CONVERSION_MODE_CONTINUOUS = 2


def MAX11210_begin(proxy):
    proxy.MAX11210_setDefault();
    proxy.MAX11210_setLineFreq(60);  # 60 Hz
    proxy.MAX11210_setInputRange(INPUT_RANGE_UNIPOLAR);
    proxy.MAX11210_setClockSource(CLOCK_SOURCE_INTERNAL);
    proxy.MAX11210_setEnableRefBuf(True);
    proxy.MAX11210_setEnableSigBuf(True);
    proxy.MAX11210_setFormat(FORMAT_OFFSET);
    proxy.MAX11210_setConvMode(CONVERSION_MODE_SINGLE);
    proxy.MAX11210_selfCal();
    proxy.MAX11210_sysOffsetCal();
    proxy.MAX11210_sysGainCal();

from collections import OrderedDict
import pandas as pd

MAX11210_begin(proxy)
calibration_settings = \
    pd.Series(OrderedDict([('SelfCalGain', proxy.MAX11210_getSelfCalGain()),
                           ('SelfCalOffset', proxy.MAX11210_getSelfCalOffset()),
                           ('SysGainCal', proxy.MAX11210_getSysGainCal()),
                           ('SysOffsetCal', proxy.MAX11210_getSysOffsetCal())]))
print '# Calibration settings #\n'
print calibration_settings

print '# Register statuses #\n'
print '----- STAT1 -----\n' + max11210_adc_ui.format_STAT1(proxy.MAX11210_getSTAT1()) + '\n'
print '----- CTRL1 -----\n' + max11210_adc_ui.format_CTRL1(proxy.MAX11210_getCTRL1()) + '\n'
# print '----- CTRL2 -----\n' + str(format(proxy.MAX11210_getCTRL2(),'b')) + '\n'
print '----- CTRL3 -----\n' + max11210_adc_ui.format_CTRL3(proxy.MAX11210_getCTRL3())

%matplotlib inline
import datetime as dt

import matplotlib as mpl
import matplotlib.ticker
import si_prefix as si
from IPython.display import display


formatter = mpl.ticker.FuncFormatter(lambda x, *args: si.si_format(x, 3))

Vref = 3.0 #Reference Voltage 3.0 V

def _pmt_read(*args):
    
#     proxy.MAX11210_setConvMode(CONVERSION_MODE_SINGLE)
    proxy.MAX11210_setGain(adc_gain.value)
    raw_values = max11210_adc_ui.MAX11210_read(proxy, pmt_rate.value, pmt_duration.value)
    print 'Sampling Rate: ' + str(pmt_rate.value) + ' Hz'
    print 'Digital Gain: ' + str(adc_gain.value)
    voltage = (raw_values / (2 ** 24 - 1))*(Vref/adc_gain.value)
    current = voltage / 30e3  # 30 kOhm
    
    current.to_clipboard()
    
    axis = current.plot()
    axis.yaxis.set_major_formatter(formatter)

    
pmt_rate = ipw.Dropdown(description='Sample rate (Hz)',
                        options=(1, 2, 5, 10, 15, 30, 60, 120), value=1)
adc_gain = ipw.Dropdown(description='Digital Gain',
                        options=(OrderedDict([('X1',1),('X2',2),('X4',4),('X8',8),('X16',16)])), value=1)
pmt_duration = ipw.FloatSlider(description='PMT duration (s)', min=1,
                               max=1000, value=10)

pmt_read = ipw.Button(description='Read PMT')
pmt_read.on_click(_pmt_read)

ipw.VBox([pmt_rate,adc_gain, pmt_duration, pmt_read])

"""
Explanation: MAX11210 ADC
End of explanation
"""


