#!   /usr/bin/env   python
#    coding: utf8

# Copyright CERN, 2011
# Author: Matthieu Cattin <matthieu.cattin@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org

import sys
import rr
import time
import os

from ptsexcept import *

import csr
import fmc_adc
import spec_fmc_adc


"""
test13: Test 1-wire thermometer and read the unique ID of the SPEC board.

Note: Requires test00.py to run first to load the firmware!
"""


GN4124_CSR = 0x0

FAMILY_CODE = 0x28

def main (default_directory='.'):

    load_firmware = raw_input('Do you want to load the firmware? [y,n]')
    if(load_firmware == 'y'):
        path_fpga_loader = '../../../gnurabbit/user/fpga_loader';
        path_firmware = '../firmwares/spec_fmcadc100m14b4cha_test.bin';

        firmware_loader = os.path.join(default_directory, path_fpga_loader)
        bitstream = os.path.join(default_directory, path_firmware)
        print firmware_loader + ' ' + bitstream
        os.system( firmware_loader + ' ' + bitstream )

        time.sleep(2);

    # Objects declaration
    spec = rr.Gennum() # bind to the SPEC board
    fmc = fmc_adc.CFmcAdc100Ms(spec)
    spec_fmc = spec_fmc_adc.CSpecFmcAdc100Ms(spec)

    print('\nSPEC 1-wire thermo/ID test')

    # Read SPEC unique ID and print to log
    spec_unique_id = spec_fmc.get_unique_id()
    if(spec_unique_id == -1):
        raise PtsError ("Can't read DS18D20 1-wire thermometer on SPEC board.")
    else:
        print('SPEC Unique ID: %.12X') % spec_unique_id

    # Read FMC unique ID and print to log
    fmc_unique_id = fmc.get_unique_id()
    if(fmc_unique_id == -1):
        raise PtsError ("Can't read DS18D20 1-wire thermometer on SPEC board.")
    else:
        print('FMC Unique ID:  %.12X') % fmc_unique_id

    # Read temperatur and print to log
    temp = spec_fmc.get_temp()
    print('SPEC temperature: %3.3f°C') % temp

    if((spec_unique_id & 0xFF) != FAMILY_CODE):
        family_code = spec_unique_id & 0xFF
        print('family code: 0x%.8X') % family_code
        raise PtsError ("SPEC's 1-wire thermometer has the wrong family code:0x.2X expected:0x%.2X" % family_code,FAMILY_CODE)


    for i in range(1000):
        print('%4d: spec: %3.3f°C    fmc: %3.3f°C') %(i, spec_fmc.get_temp(),fmc.get_temp())
        time.sleep(.5)


if __name__ == '__main__' :
    main()
