import threading
from gpiozero import Button, OutputDevice, Buzzer, PWMLED
from time import sleep
from datetime import datetime

segledSclk = OutputDevice(20)
segledDio = OutputDevice(21)
segledRclk = OutputDevice(26)

sevenSeg = { # Patterns to display some ASCII characters.
    ' ':0x00, '"':0x22, "'":0x20, ',':0x10, '-':0x40, '.':0x80, '0':0x3F, '1':0x06,
    '2':0x5B, '3':0x4F, '4':0x66, '5':0x6D, '6':0x7D, '7':0x07, '8':0x7F, '9':0x6F,
    ':':0x09, ';':0x0D, '<':0x61, '=':0x48, '>':0x43, '?':0xD3, '@':0x5F, 'A':0x77,
    'C':0x39, 'E':0x79, 'F':0x71, 'G':0x3D, 'H':0x76, 'I':0x30, 'J':0x1E, 'L':0x38,
    'O':0x3F, 'P':0x73, 'S':0x6D, 'U':0x3E, '[':0x39, ']':0x0F, '^':0x23, '_':0x08,
    '`':0x02, 'b':0x7C, 'c':0x58, 'd':0x5E, 'h':0x74, 'i':0x10, 'n':0x54, 'o':0x5C,
    'q':0x67, 'r':0x50, 't':0x78, 'u':0x1C, 'y':0x6E, '|':0x30, '~':0x01
}

def lookup(c):
    global sevenSeg
    pattern = 0 # Default to blank if pattern can't be found.
    if c in sevenSeg:
        pattern = sevenSeg[c]
    elif c.isupper() and c.lower() in sevenSeg:
        pattern = sevenSeg[c.lower()]
    elif c.islower() and c.upper() in sevenSeg:
        pattern = sevenSeg[c.upper()]

    return pattern

def shift(b):
    """ Shift one byte of data (MSB first) into the 74HC595 shift registers """
    for mask in [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01]:
        segledSclk.off() # falling edge of shift register clock does nothing
        if b & mask:
            segledDio.on()
        else:
            segledDio.off()
        segledSclk.on() # rising edge of shift register clock shifts one bit

def segled(pattern, address):
    """ Write to the shift registers that drive the 7-segment LEDS.
    Psttern is a byte that switches on segments (and decimal points) - bits active high.
    Address controls which of the four characters are illuminated: 1 2 4 8.
    Address 0 switches off all characters.  Address (e.g. 9) may select more than
    one character - but the same pattern will be written to each illuminated character.
    To drive a separate pattern to each character (e.g. "1234") requires muliplexing.
    """
    segledRclk.off() # Decouple shift registers from LED outputs.
    shift(pattern) # First, shift in the pattern to display...
    shift(~address) # then, shift in the address (in bits 0~3 of second byte, active low).
    segledRclk.on() # Update LED outputs from shift registers.

def multiplex(display):
    """ display is a function that returns a two-item tuple.
    The first item is a string of up to 4 characters that will be displayed, right justified.
    If the first item is a zero-length string, then the display is cleared and the multiplexing stops.
    The second item is an integer, 0 to 15, that controls which, if any, decimal points are illuminated.
    The addresses of the decimal points go: 1 2 4 8.
    """
    oldString = ""
    oldDP = 0
    index = 0 # Position of character currently illuminated: 3 2 1 0.
    while display()[0] != "": # Loop until a blank display is requested.
        if (display()[0] != oldString) or (display()[1] != oldDP):
            oldString = display()[0]
            s = (oldString[::-1] + "    ")[:4] # Reverse string and pad/truncate to 4 characters.
            oldDP = display()[1] & 0x0F
            patterns = []
            for i in range(4):
                 patterns.append(lookup(s[i]))
                 if oldDP & (8 >> i):
                    patterns[i] |= 0x80 # Add any decimal points.
        segled(patterns[index], 8 >> index)
        sleep(0.005)
        index = (index + 1) & 3
    segled(0, 0) # Blank display and terminate thread.

# Start LEDS pulsing
led1 = PWMLED(19, active_high = False)
led1.blink(on_time = 0, off_time = 0, fade_in_time = 0.5, fade_out_time = 0.5)
# led2 (GPIO16) doesn't work on my old non-WiFi Pi - I think the pin is used for the activity led
led3 = PWMLED(12, active_high = False)
led3.blink(on_time = 0, off_time = 0, fade_in_time = 1, fade_out_time = 1)

buzzer = Buzzer(13)
buzzer.off()

# A thread for driving the display in multiplex mode.
thread = threading.Thread(target = multiplex, args = (lambda: display, ), daemon = True)

# Pressing s2 (red button) exits program.
s2button = Button(18)
def exitProgram():
    global display, thread
    buzzer.off()
    if thread.is_alive():
        display = ("", 0) # Request thread to exit.
        sleep(0.1) # Give thread time to stop mulitplexing.
    segled(lookup('0'), 8) # Leave display showing (non multiplexed) 0 on exit.
    exit()
s2button.when_pressed = exitProgram

# Each press of s1 (blue button) moves to next display mode.
s1button = Button(27, bounce_time = 0.05)

NUM_DISPLAY_MODES = 6
displayMode = 0 # Increments when s1button pressed.
def s1pressed():
    global displayMode
    i = displayMode + 1
    if i >= NUM_DISPLAY_MODES:
        i = 0
    displayMode = i
s1button.when_pressed = s1pressed

oldDisplayMode = -1 # Main thread can mostly sleep until displayMode changes.
while True:
    if displayMode != oldDisplayMode: # User has pressed button (or first pass).
        oldDisplayMode = displayMode
        if displayMode == 0:
            display = ("bLUE", 0) # Prompt (assume s1 button is blue, like mine).
            if thread.is_alive() == False:
                thread.start()
        elif displayMode == 1:
            display = ("PLAy", 0)
        elif displayMode == 2:
            display = ("HELP", 0)
            buzzer.on()
        elif displayMode == 3:
            buzzer.off()
            display = ("9876",  1) # 9.876
        elif displayMode == 4:
            display = ("CLOC", 0)
            sleep(1)
        elif displayMode == 5:
            display = ("SECS", 0)
            sleep(1)
    elif displayMode == 4: # Clock display (HH.MM).
        now = datetime.now()
        dp = 2 if now.microsecond < 500000 else 0
        display = (now.strftime("%H%M"), dp)
        sleep(0.1)
    elif displayMode == 5: # Seconds display (MM.SS).
        now = datetime.now()
        dp = 2 if now.microsecond < 500000 else 0
        display = (now.strftime("%M%S"), dp)
        sleep(0.1)
    else:
        sleep(0.1) # Button not pressed so sleep for a bit.
