#
# config file for train controller
#
# holds global variables and flags

# debug level: set to
#    0 for no debug output
#    1 status output
#    2 full debug output
#
# to support debug slow_loop could be set to 1. This inserts a half second delay between loops to ease debugging

debug = 0

from mcp42xxx import MCP42xxx
from machine import SPI, Pin, ADC

# instantiate SPI interface and digital potentiometers for track power supplies

# define SPI chip select Pin and set Pin to high (inactive) on instatiation
CS_pin = Pin(20, Pin.OUT, value=1)
spi = SPI(0, baudrate=400_000, bits=8, sck=Pin(18), mosi=Pin(19))
track_power = MCP42xxx(spi, CS_pin, debug=debug)


# define pins for track controller rail1 and rail2
# enable pin is initialized with value=0 to switch off rail power on start up
# rail LEDs are turned off

R1Ovl = Pin(8, Pin.IN)
R1Dir = Pin(9, Pin.OUT)
R1Enable = Pin(10, Pin.OUT, value=0)
R1OLreset = Pin(11, Pin.OUT)
rail1_LED = Pin(6, Pin.OUT, value=0)

R2Ovl = Pin(12, Pin.IN)
R2Dir = Pin(13, Pin.OUT)
R2Enable = Pin(14, Pin.OUT, value=0)
R2OLreset = Pin(15, Pin.OUT)
rail2_LED = Pin(7, Pin.OUT, value=0)

# instantiate ADCs to read speed and direction potentiometers
rail1_pot = ADC(Pin(26))    # ADC0 to read Potentiometer 1
rail2_pot = ADC(Pin(27))    # ADC1 to read Potentiometer 2
# ADC values are 0-65535
ADCmax = 65535
ADCmin = 0

# Potentiometers to set speed and direction have a stop position in the middle using a dead band
# increase dead band value if stop is hard to hit
dead_band_value = .1     # 10% of max pot value
Pot_mid_point = int(ADCmax/2)
dead_band = int(Pot_mid_point * dead_band_value)
stop_lower = Pot_mid_point - dead_band
stop_upper = Pot_mid_point + dead_band

# train engine characteristics
# these values are used to adjust the power suplly output when the trains starts moving from a stop
# value range is 0 to 255
break_free = 121
min_speed = 86
# break free time in ms, increase if engine does not start at break free power setting, decrease if engine does over-accelerate
break_free_time = 1000

# define rail status dictionaries which keep current state of rails
rail1_status = {"direction": "stop",
                "power": "off",
                "speed": 0,
                "overload": False}

rail2_status = {"direction": "stop",
                "power": "off",
                "speed": 0,
                "overload": False}
