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

# Copyright CERN, 2011
# Author: Matthieu Cattin (CERN)
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org
# Last modifications: 03/05/2012

# Import standard modules
import sys
import time

# Import specific modules
from spi import *

# Class to access the MAX5442 (DAC) chip.
# It uses the SPI class.

class MAX5442OperationError(Exception):
    def __init__(self, addr, msg):
        self.msg = msg
        self.addr = addr # addr corresponds to the SPI slave number
    def __str__(self):
        return ("MAX5442 [SPI slave number:%d]: %s" %(self.addr, self.msg))

class CMAX5442:

    def __init__(self, spi, slave):
        self.spi = spi
        self.slave = slave

    # value = DAC digital value (2 bytes)
    def set_value(self, value):
        try:
            tx = [(value & 0xFF), ((value & 0xFF00)>>8)]
            #print '[max5442] Value to set: %.4X' % value
            #for i in range(len(tx)):
            #    print '[max5442] tx[%d]: %.2X' %(i, tx[i])
            self.spi.transaction(self.slave, tx)
        except SPIDeviceOperationError as e:
            raise MAX5442OperationError(self.slave, e)

