import wiringpi
from time import sleep

base = 65
i2c = 0x20

timer = 0.7
pins = {"A0" : 9,#
        "A1" : 6,#
        "A2" : 8,#
        "D0" : 7,
        "RUN" : 0,#
        "E1" : 10,#
        "E2" : 5,
        "E3" : 11,#
        "E4" : 4,
        "E5" : 12,#
        "E6" : 3,
        "E7" : 13,
        "E8" : 2,
        "E9" : 9,#PGIO06 wegen fehlender Porterweiterung
        "E10" : 10,#GPIO12 wegen fehlender Porterweiterung
        "E11" : 14,#
        "E12" : 1,
        "E13" : 15 }#

"""
A0 = 3
A1 = 2
A2 = 1
D0 = 17
E13 = 15
RUN = 16
E1 = 5
E2 = 6
E3 = 7
E4 = 8
E5 = 9
E6 = 10
E7 = 11
E8 = 12
E9 = pi
E10 = pi
E11 = 13
E12 = 14
E13 = 15
"""
"""
GPA0 0= 16
GPA1 1= 14
GPA2 2= 12
GPA3 3= 10
GPA4 4= 8
GPA5 5= 6
GPA6 6= 2
GPA7 7= 17
GPB0 8= 1
GPB1 9= 3
GPB2 10= 5
GPB3 11= 7
GPB4 12= 9
GPB5 13= 11
GPB6 14= 13
GPB7 15= 15

"""
for key in pins.keys():
  pins[key] += base

pins["E9"] -= base
pins["E10"] -= base

def init():
  wiringpi.wiringPiSetupGpio()
  wiringpi.mcp23017Setup(base, i2c)
  for i in pins.values():
    wiringpi.pinMode(i, 1)
    wiringpi.digitalWrite(i, 1)
  data(0)
  wiringpi.digitalWrite(pins["RUN"], 0)

def data(value):
  wiringpi.digitalWrite(pins["D0"], value)
  
def select_latch(latch):
  deselect_latches()
  wiringpi.digitalWrite(pins["E" + str(latch)], 0)

def deselect_latches():
  for i in range(1,14):
    wiringpi.digitalWrite(pins["E" + str(i)], 1)
 
def select_pin(pin):
  wiringpi.digitalWrite(pins["A0"], pin & 0b001)
  wiringpi.digitalWrite(pins["A1"], pin & 0b010)
  wiringpi.digitalWrite(pins["A2"], pin & 0b100)

def trigger_pin(latch, pin, t=timer):
  select_latch(latch)
  select_pin(pin)

  data(1)
  sleep(t)
  data(0)

def rotate():
  for i in range(1, 14):
    for j in range(8):
      trigger_pin(i, j)
      print("activated latch "+str(i)+ "\t pin "+str(j))

def activate_all_lamps():
  for latch in range(1,11):
    for pin in range(8):
      data(1) 
      select_latch(latch)
      select_pin(pin)
      sleep(0.03)
def all_lamps():
  activate_all_lamps()

def outhole():
  trigger_pin(11,0)
def right_kicker():
  trigger_pin(12,5)

def right_flap():
  trigger_pin(13,5,0.4)

def right_bank():
  trigger_pin(13,2,0.4)

def activate_pin(latch, pin):
  select_latch(latch)
  select_pin(pin)
  data(1)
  deselect_latches()

def deactivate_pin(latch, pin):
  select_latch(latch)
  select_pin(pin)
  data(0)
  deselect_latches()
def activate_flipper():
  activate_pin(8, 4)

def activate_top_flipper():
  activate_pin(12, 4)

def deactivate_flipper():
  deactivate_pin(8, 4)

def deactivate_top_flipper():
  deactivate_pin(12, 4)

init()
