import time
import socket
from kbhit import KBHit

UDP_IP = "192.168.1.199"
UDP_PORT = 1111
STATUS_INTERVAL = 500


client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.settimeout(0.25)
addr = (UDP_IP, UDP_PORT)

kb = KBHit()

LOG_FILE = 'logs\\' + str(int(time.time())) + '.log'

# send a dummy command to start
client_socket.sendto(("FFS" + str(STATUS_INTERVAL)).encode(), addr)

while True:

    # check for user input
    if kb.kbhit():
        c = kb.getch()
        if ord(c) == 27: # ESC
            # turn off status messages before exit
            client_socket.sendto("FFS0".encode(), addr)
            break
        else:
            cmd = input("CMD: ")
            client_socket.sendto(cmd.encode(), addr)

    try:
        data, server = client_socket.recvfrom(1024)
        utf8_data = data.decode('utf-8').rstrip('\r\n')
        print(utf8_data)
        with open(LOG_FILE,'a+') as f:
            f.write(str(time.time()) + ' : ' + utf8_data + '\n')
    except socket.timeout:
        pass
        #print('REQUEST TIMED OUT')