import socket,cv2, pickle,struct,time
import RPi.GPIO as GPIO
import gpiod

client_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
host_ip = '192.168.4.3' # paste your server ip address here
port = 8000
client_socket.connect((host_ip,port)) # a tuple
print('connect')

LED_PIN = 17
buzzer_pin = 12 # replace with the correct GPIO pin number for your buzzer
chip = gpiod.Chip('gpiochip4')

led_line = chip.get_line(LED_PIN)
buzzer_line = chip.get_line(buzzer_pin)

led_line.request(consumer="LED", type=gpiod.LINE_REQ_DIR_OUT)
buzzer_line.request(consumer='my_app', type=gpiod.LINE_REQ_DIR_OUT)


payload_size = struct.calcsize("Q")
data = b""

try:
    # In the Raspberry Pi code, after connecting to the server, add:
    while True:
        while len(data) < payload_size:
            packet = client_socket.recv(4*1024) # 4K
            if not packet: break
            data+=packet
        packed_msg_size = data[:payload_size]
        data = data[payload_size:]
        packed_msg_size += b' ' * (8 - len(packed_msg_size))
        msg_size = struct.unpack("Q",packed_msg_size)[0]

        while len(data) < msg_size:
            data += client_socket.recv(4*1024)

        message = data[:msg_size]
        data = data[msg_size:]
        print("Received message: ", message)

        if message == b'1': # if message is '1' then turn on buzzer and led
            led_line.set_value(1)
            buzzer_line.set_value(1)
            print('led and buzzer on')
            time.sleep(1)
            led_line.set_value(0)
            buzzer_line.set_value(0)
            print('led and buzzer off')
        elif message == b'0': # if message is '0' then turn off buzzer and led
            led_line.set_value(0)
            buzzer_line.set_value(0)
            print('led and buzzer off')

except KeyboardInterrupt:
    print('Program stopped by user.')

finally:
    # Destroy all the windows
    cv2.destroyAllWindows()
    GPIO.cleanup()