#!   /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


"""
test01: Test 1-wire thermometer and read the unique ID.

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

CARRIER_CSR = 0x30000

CSR_TYPE_VER = 0x00
CSR_BSTM_TYPE = 0x04
CSR_BSTM_DATE = 0x08
CSR_STATUS = 0x0C
CSR_CTRL = 0x10

PCB_VER_MASK = 0x000F
CARRIER_TYPE_MASK = 0xFFFF0000

STATUS_FMC_PRES = (1<<0)
STATUS_P2L_PLL_LCK = (1<<1)
STATUS_SYS_PLL_LCK = (1<<2)
STATUS_DDR3_CAL_DONE = (1<<3)

CTRL_LED_GREEN = (1<<0)
CTRL_LED_RED = (1<<1)
CTRL_DAC_CLR_N = (1<<2)

FAMILY_CODE = 0x28

def main (default_directory='.'):

    """
    path_fpga_loader = '../../../gnurabbit/user/fpga_loader';
    path_firmware = '../firmwares/spec_fmcadc100m14b4cha.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
    carrier_csr = csr.CCSR(spec, CARRIER_CSR)
    fmc = fmc_adc.CFmcAdc100Ms(spec)

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

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


if __name__ == '__main__' :
    main()
