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

'''
A machinekit/LinuxCNC user module for Replicape A4 hardware config

Controlling various parameters that are exposed through bit-shifters.

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

The following pins are exported
* enable [IN]
  Enable the steppers
* stepper.x.microstepping [IN]
  Microstepping settings for steppers 0 to 5.
  Value is treated as 1/2^x, e.g. 5 means 1/32 microstepping mode.
* stepper.x.decay [IN]
  True for slow decay
* 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_shifter = None

# Load SPI module
try:
    # Init the SPI for the serial to parallel
    try:
        spi_shifter = SPI((0, 1))
    except IOError:
        spi_shifter = SPI((1, 1))
    spi_shifter.mode = 0
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
microsteppingPins = [None] * N
decayPins = [None] * N

for i in range(0,N):
    microsteppingPins[i] = h.newpin(("stepper.%d.microstepping" % i), hal.HAL_U32, hal.HAL_IN)
    decayPins[i] = h.newpin(("stepper.%d.decay" % i), hal.HAL_BIT, hal.HAL_IN)
halWatchdogPin = h.newpin("watchdog", hal.HAL_BIT, hal.HAL_OUT)
h.ready()

'''
The bits in the shift register are as follows (Rev A4) :
Bit - name   - init val 
D0 = -       = Don't Care
D1 = MODE2   = 0  
D2 = MODE1   = 0
D3 = MODE0   = 0
D4 = nENABLE = 0  - Enabled
D5 = DECAY   = 0  - Slow decay 
D6 = nSLEEP  = 1  - Not sleeping 
D7 = nRESET  = 1  - Not in reset mode
'''

def commit():
    ''' Turn on the stepper chips '''

    # Writing the modes
    bytes = []
    for i in range(0,N):
        state = decayPins[i].value << 5 | \
                ((microsteppingPins[i].value & 0x04) >> 2) << 1 | \
                ((microsteppingPins[i].value & 0x02) >> 1) << 2 | \
                ((microsteppingPins[i].value & 0x01) >> 0) << 3 | \
                0 << 4 | 1 << 6 | 1 << 7
        bytes.append(state)
    # Reverse the writting orders due to serial chain sequence
    spi_shifter.write(bytes[::-1]) 

def reset():
    ''' Reset the stepper chip '''
    bytes = []
    for i in range(0,N):
        state = 1 << 4 | 0 << 6 | 0 << 7
        bytes.append(state)
    # Reverse the writting orders due to serial chain sequence
    spi_shifter.write(bytes[::-1]) 
    
def turnOff():
    ''' Turn off all stepper chips '''
    bytes = []
    for i in range(0,N):
        state = 1 << 4 | 0 << 6 | 1 << 7
        bytes.append(state)
    # Reverse the writting orders due to serial chain sequence
    spi_shifter.write(bytes[::-1]) 

watchdog = True
try:
    oldEnable = False
    reset()
    time.sleep(0.05)
    while (True):
        enable = enablePin.value
        if (enable and not oldEnable):
            commit()
        if (oldEnable and not enable):
            turnOff()
        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()

