#!/usr/bin/python

# Author: Tomasz?
# Author (modifications): Richard Carrillo <rcarrillo(AT)sevensols.com>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org
# Website: http://www.sevensols.com
# Last modifications: 1/4/2012

from i2c import *

class CDAC5578:

   CMD_POWER_ON = 0x40
   CMD_WRITE_CH = 0x30
   CMD_SW_RESET = 0x70
   CMD_LDAC_CTRL = 0x60
   CMD_READ_REG = 0x10
	 
   def __init__(self, bus, addr):
      """ Configure DAC """
      self.bus = bus;
      self.addr = addr;
      self.cmd_out(self.CMD_SW_RESET,  0);
      self.cmd_out(self.CMD_LDAC_CTRL, 0xff); # ignore LDAC pins
      self.cmd_out(self.CMD_POWER_ON, 0x1f, 0xe0);

   def cmd_out(self, cmd, data, data2 = 0):
      """ Send a command to DAC which does not include answer """
      self.bus.start(self.addr, True);
      self.bus.write(cmd, False)
      self.bus.write(data, False)
      self.bus.write(data2, True)

   def cmd_in(self, cmd):
      """ Send a command to DAC  which expects answer """
      self.bus.start(self.addr, True)
      self.bus.write(cmd, False)
      self.bus.start(self.addr, False)
      reg_val=self.bus.read(False)
      self.bus.read(True)
      return(reg_val)

   def out(self, channel, data):
      """ Set a value (data) to a specified DAC channel """
      self.cmd_out(self.CMD_WRITE_CH | channel, data)

   def rd_out(self, channel):
      """ Return the value set to a specified DAC channel """
      return(self.cmd_in(self.CMD_READ_REG | channel))

