#!/usr/bin/env python


import sys
import socket
import os
import subprocess as sp
import time
import fcntl
import errno
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.IN, GPIO.PUD_UP)
GPIO.add_event_detect(17, GPIO.FALLING)


def browser(url, h_long):
    b = sp.Popen(['iceweasel', url])
    time.sleep(h_long)
    b.terminate()
    
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:
        if GPIO.event_detected(17):
	    time.sleep(0.05)
	    browser('http://'+ add + ':8082', 120)
	    time.sleep(1)
	try:
            data = s.recv(1024)
        except socket.error, e:
            continue
        else:
	    if data == (b'run'):
                browser('http://'+ add + ':8082', 60)
                print('Nekdo zvonil ' + time.strftime('%Y-%m-%d-%H-%M'))
            continue
except KeyboardInterrupt:
    pass
finally:
    print('Exit')
    s.close()
        






