import socket
import struct

STM32_IP = "192.168.10.2"
STM32_PORT = 5000

PAYLOAD_SIZE = 50 * 1024


def make_payload(size):
    return bytes([i % 256 for i in range(size)])


def main():

    payload = make_payload(PAYLOAD_SIZE)

    print(f"Payload size: {len(payload)} bytes")

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:

        print(f"Connecting to STM32 {STM32_IP}:{STM32_PORT} ...")

        sock.connect((STM32_IP, STM32_PORT))

        print("Connected")

        # Step 1: Send 4-byte payload length
        length_data = struct.pack("!I", len(payload))

        sock.sendall(length_data)

        print(f"Payload length sent: {len(payload)} bytes")

        # Step 2: Send 50 KB payload
        sock.sendall(payload)

        print(f"Payload sent successfully: {len(payload)} bytes")

        # Step 3: Wait for ACK from STM32
        ack_data = sock.recv(64)

        if ack_data:

            ack_text = ack_data.decode().strip()

            print(f"ACK from STM32: {ack_text}")

        else:

            print("No ACK received")

    print("Connection closed")


if __name__ == "__main__":
    main()