import socket,cv2, pickle,struct,time
import RPi.GPIO as GPIO

# Open a connection to the webcam (0 is the default camera, using DirectShow backend)
cap = cv2.VideoCapture(0)
# Check if the webcam is opened correctly
if not cap.isOpened():
    print("Error: Could not open webcam.")
    exit()

pir_pin = 27
# Set up the GPIO mode
GPIO.setmode(GPIO.BCM)
# Set up GPIO pin 27 as an input
GPIO.setup(pir_pin, GPIO.IN)
pir_detect = 0

# This function will be called when a change is detected
def motion_detected(channel):
    global pir_detect
    pir_detect = 1
    print("Motion Detected!")
    global start_time
    start_time = time.time()

# Add event to detect a rising edge on the PIR output pin
GPIO.add_event_detect(pir_pin, GPIO.RISING, callback=motion_detected)

try:
    while True:
        while pir_detect ==1:
            # create socket
            client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            host_ip = '192.168.4.3' # paste your server ip address here
            port = 9999
            client_socket.connect((host_ip,port)) # a tuple
            on_off_var = 1

            while on_off_var:


                while(cap.isOpened()):
                    img,frame = cap.read()
                    a = pickle.dumps(frame)
                    message = struct.pack("Q",len(a))+a
                    client_socket.sendall(message)
                        
                    cv2.imshow('TRANSMITTING VIDEO',frame)
                    key = cv2.waitKey(1) & 0xFF
                    if key ==ord('q'):
                        client_socket.close()

                if time.time() - start_time >60:
                    client_socket.close()
                    on_off_var = 0

except KeyboardInterrupt:
    print('Program stopped by user.')

finally:
    # After the loop release the cap object
    cap.release()

    # Destroy all the windows
    cv2.destroyAllWindows()