import RPi.GPIO as GPIO
import time
import select
import sys

displayVccPinToBoardPin = {6:22, 9:24, 10:26, 12:23, 13:21, 15:19, 16:15, 17:13, 18:11, 19:7, 20:5, 21:3, 30:22}
displayGroundPinToBoardPin = {1:12, 2:16}

displayDigits = [ 
None, # 1st digit
# 2nd digit
[
[[9,12,13],[10,12,13]], # 0
[[],[10,12]], # 1
[[9,10,12],[10,13]], # 2
[[10,12],[10,12,13]], # 3
[[10,13],[10,12]], # 4
[[10,12,13],[12,13]], # 5
[[9,10,12,13],[12,13]], # 6
[[],[10,12,13]], # 7
[[9,10,12,13],[10,12,13]], # 8
[[10,12,13],[10,12,13]], # 9
],
# 3rd digit
[
[[15,16,17],[15,17,18]], # 0
[[16,17],[]], # 1
[[15,16],[16,17,18]], # 2
[[15,16,17],[16,17]], # 3
[[16,17],[15,16]], # 4
[[15,17],[15,16,17]], # 5
[[15,17],[15,16,17,18]], # 6
[[15,16,17],[]], # 7
[[15,16,17],[15,16,17,18]], # 8
[[15,16,17],[15,16,17]], # 9
], 
[ # 4th digit:
[[18,20,21],[19,20,21]], # 0
[[],[19,20]], # 1
[[18,19,20],[19,21]], # 2
[[19,20],[19,20,21]], # 3
[[19,21],[19,20]], # 4
[[19,20,21],[20,21]], # 5
[[18,19,20,21],[20,21]], # 6
[[],[19,20,21]], # 7
[[18,19,20,21],[19,20,21]], # 8
[[19,20,21],[19,20,21]] # 9
],
[[[30],[]]] # colon
] # end digits

# set numbering mode to match board
GPIO.setmode(GPIO.BOARD)

dp = displayVccPinToBoardPin
gp = displayGroundPinToBoardPin

for (d,b) in (dp.items()+gp.items()):
	GPIO.setup(b,GPIO.OUT)
	
def setAllToLow():
	for (d,b) in (dp.items()+gp.items()):
		GPIO.output(b,GPIO.LOW)

multiplexedDigits = []
	
def readstdin():
	if select.select([sys.stdin],[],[],0.01)[0] != []:
		#print >> sys.stderr, "Reading..."
		line = sys.stdin.read(5).strip("\n") # :123\n
		if line == "":
			time.sleep(0.01)
			sys.exit(0)
		#print >> sys.stderr, "Line:\"%s\""%line
		del multiplexedDigits[:]
		if line.find(':') != -1:
				multiplexedDigits.append(displayDigits[4][0])
		line = line.translate(None, ':')
		for index, char in enumerate(line):
			if char != ' ':
				digit = int(char)
				multiplexedDigits.append(displayDigits[1+index][digit])

activeGround = 1
while True:
	setAllToLow()
	if activeGround == 1 :
		activeGround = 2
	else:
		activeGround = 1
	GPIO.output(gp[activeGround],GPIO.HIGH)
	for multiplexedDigit in multiplexedDigits:
		for pin in multiplexedDigit[activeGround-1]:
			GPIO.output(dp[pin],GPIO.HIGH)
	readstdin()
