#!/usr/bin/python
# encoding: utf-8 
# vim: set sw=4 sts=4 et:

'''
A machinekit/LinuxCNC user module for Replicape A4A DAC control
Interface with DAC088S085 on SPI for stepper driver current limit

The settings are populated when the "enable" pin is turned on (rising edge)

The following pins are exported
* enable
  Enable the steppers
* x.current
  Current settings for steppers 0 to 4.
  Value is treated as current in Amps
* watchdog
  A pin that toggles at every loop informing HAL that this component is alive

Copyright (C) 2013 Sam Wong

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'''

import argparse
import glob
import sys
import time

import hal
from spi import SPI

parser = argparse.ArgumentParser(description='HAL component to configure Replicape hardware')
parser.add_argument('-n','--name', help='HAL component name',required=True)
args = parser.parse_args()

# Initialize SPI
spi_dac = None

# Load SPI module
try:
    # init the SPI for the DAC
    try:
        spi_dac = SPI((0, 0))
    except IOError:
        spi_dac = SPI((1, 0))
    spi_dac.mode = 1

except IOError:
    print("Unable to set up SPI")
    exit(-1)

# Initialize HAL
h = hal.component(args.name)
enablePin = h.newpin("enable", hal.HAL_BIT, hal.HAL_IN)

N = 5 # We have 5 steppers
currentPins = [0] * N

vRef = 3.3
rSense = 0.1

for i in range(0,N):
    currentPins[i] = h.newpin(("%d.current" % i), hal.HAL_FLOAT, hal.HAL_IN)
halWatchdogPin = h.newpin("watchdog", hal.HAL_BIT, hal.HAL_OUT)
h.ready()

def commit():
    # Writing the current
    for i in xrange(N):
        vOut = currentPins[i].value * 5.0 * rSense
        dacVal = int((vOut * 256.0) / vRef)
        spi_dac.write([                          \
            (dacVal & 0xF0) >> 4 | (i << 4),    \
            (dacVal & 0x0F) << 4])
    spi_dac.write([0xA0, 0xFF]) # Commits to output

watchdog = True
try:
    oldEnable = False
    commit()
    time.sleep(0.05)
    while (True):
        enable = enablePin.value
        if (enable and not oldEnable):
            commit()
        oldEnable = enable

        watchdog = not watchdog
        halWatchdogPin.value = watchdog
        time.sleep(0.05)
except BaseException as e:
    reset()
    print(("exiting HAL component %s: %s") % (args.name, e))
    h.exit()

