# Jack Leijssen de PA1W 18-okt-2015
# Raspberry Pi beacon software
# call as administrator => sudo python Morse2Pi.py

import RPi.GPIO as GPIO
import time
import curses

GPIO.setwarnings(False) #supress warnings
# Set the mode of the output pin. 
GPIO.setmode(GPIO.BOARD) 
# GPIO pin 10 is the output. 
GPIO.setup(10, GPIO.OUT) 

#returns ms
def millisec_time():
        return time.time() * 1000

def get_millisec_time(howlong2wait):
    start = millisec_time()
    while ( (start + howlong2wait) > millisec_time() ):
        pass

CODE = {'A': '.-',     'B': '-...',   'C': '-.-.', 
        'D': '-..',    'E': '.',      'F': '..-.',
        'G': '--.',    'H': '....',   'I': '..',
        'J': '.---',   'K': '-.-',    'L': '.-..',
        'M': '--',     'N': '-.',     'O': '---',
        'P': '.--.',   'Q': '--.-',   'R': '.-.',
     	'S': '...',    'T': '-',      'U': '..-',
        'V': '...-',   'W': '.--',    'X': '-..-',
        'Y': '-.--',   'Z': '--..',
        
        '0': '-----',  '1': '.----',  '2': '..---',
        '3': '...--',  '4': '....-',  '5': '.....',
        '6': '-....',  '7': '--...',  '8': '---..',
        '9': '----.',  
	'?': '..--..', '/': '-..-.',  '.': '.-.-.-',  ',': '--..--', '=': '-...-', '-': '-....-',
	' ': ' '
        }
		
LENGTH_DIT 	= 100 # 100ms = 12wpm
stripe 		= 3*LENGTH_DIT
dot    		=   LENGTH_DIT
letter_pause  	= 2*LENGTH_DIT
word_pause    	= 4*LENGTH_DIT
 
def gen_stripe():
	GPIO.output( 10, False)	#set GPIO pin high
        get_millisec_time(stripe)
	GPIO.output(10, True)	#set GPIO pin low 
        get_millisec_time(dot)   

	
def gen_dot():
	GPIO.output( 10, False)	#set GPIO pin high
        get_millisec_time(dot)
	GPIO.output(10, True)	#set GPIO pin low 
        get_millisec_time(dot)   


def letter_space():
	GPIO.output(10, True)	#set GPIO pin low 
        get_millisec_time(letter_pause)


def word_space():
	GPIO.output(10, True)	#set GPIO pin low 
        get_millisec_time(word_pause)


def main():
	while 1:	
		msg = 'vvvvv   de PA1W/B beacon jo21rj 350mW' # raw_input('MESSAGE: ')
		bit = ''
		for char in msg:
			bit += CODE[char.upper()]
			bit += 'x' #indicates letter pause
		for char in bit:
			if char == '-': 
				gen_stripe() 
			elif char == '.':
				gen_dot()
			elif char == 'x':
				letter_space()		
			elif char == ' ':
				word_space()
		get_millisec_time(5*word_pause)

	
if __name__ == "__main__":
	try: 
		main()
	except KeyboardInterrupt:
		pass	
