#!/usr/bin/env python


import sys
import socket
import os
import subprocess as sp
import webbrowser
import time
import fcntl
import errno
from AppKit import NSBeep
#import RPi.GPIO as GPIO
#GPIO.setmode(GPIO.BCM)
#GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)
#GPIO.add_event_detect(17, GPIO.FALLING)
chrome_path = 'open -a /Applications/Google\ Chrome.app %s'


    
add = raw_input('Write IP Addres of CAM: ')

try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except (socket.error, msg):
    print('Failed to create socket')
    sys.exit()

port = 5000;

try:
    remote_ip = socket.gethostbyname(add)
    print('IP is: ' + remote_ip)
except (socket.gaierror):
    print('Host name could not be resolved. Exiting')
    sys.exit()

s.connect((remote_ip, port))
fcntl.fcntl(s, fcntl.F_SETFL, os.O_NONBLOCK)

print ('Socket Connected to ' + remote_ip)
try:
    while True:
        try:
            
            data = s.recv(1024, 0)
            if data == (b'run'):
                webbrowser.get(chrome_path).open_new('http://' + remote_ip + ':8082')
                NSBeep()
                print('Nekdo zvonil ' + time.strftime('%Y-%m-%d-%H-%M'))
        except socket.error as ex:
            if str(ex) == "[Errno 35] Resource temporarily unavailable":
                time.sleep(0)
                continue
except KeyboardInterrupt:
    pass
finally:
    print('Exit')
    s.close()
        






