from genji import API as GenjiAPI
import sys
import time
import threading
import socket
import os

import detect
import data_test
import xtea
import rsa


def detectDevChange():
    host = '127.0.0.1'
    port = 34567

    sock = socket.socket(socket.AF_INET, type=socket.SOCK_DGRAM)

    sock.bind((host,port))

    while True:
        try :
            message, cli_addr = sock.recvfrom(32)
            message = message.decode(encoding='utf-8')

            print("\n\n     ***** Genji ", message, "  *****")

            # if Genji is removed, exit the program
            if message == "removed":
                print( "      Exiting...\n\n")
                sock.close()
                break

        except KeyboardInterrupt:
            print ('\n . . .\n')
            sock.close()
            break

    os._exit(0)


# Instantiate API class in genji.py
gnjAPI = GenjiAPI()

# any Genji connected?
count = detect.detectGenji(gnjAPI)
print("")

if count < 1:
    print("No Genji Found")
    sys.exit()


 # run the thread to detect plug/unplug 
detectThread = threading.Thread(target=detectDevChange)
detectThread.start()

#let Genji API know the waiting port
gnjAPI.registerCallbackPort(34567)

# perform test over connected Genji
for dngNr in range( 1,count+1):

    print( "**********************************************")
    print( "     Performing test on Genji No.", dngNr, )
    print( "**********************************************\n")
    time.sleep(2)

    detect.led_test( gnjAPI, dngNr)
    print("")

    if data_test.data2_test(gnjAPI, dngNr) == False:
        break
    print("")

    if detect.rtc_time( gnjAPI, dngNr)==False:
        break
    print("")

    if rsa.rsa_encdec_test( gnjAPI, dngNr) == False:
        break   
    print("")

    if rsa.rsa_sign_verify_test( gnjAPI, dngNr)== False:
        break
    print("")

    if data_test.data1_test(gnjAPI,dngNr) == False:
        break
    print("")

    if xtea.xtea_test(gnjAPI, dngNr) == False:
        break
    print("")

print(" ***** Demo Over ****\n\n")
os._exit(0)