import socket as skt

class blueSPY_socket:
    def __init__(self, port = 24352, IP="127.0.0.1"):
        self.port = port
        self.IP = IP
        self.socket = skt.socket(skt.AF_INET, skt.SOCK_STREAM)
        try:
            self.socket.connect((self.IP, self.port))
        except ConnectionRefusedError as e:
            print("Failed to connecct: {}/{}", self.IP, self.port)
    
    def send(self, data):
        self.socket.sendall(data)

byte_sep = ' '
filename = 'HCI.txt'

if __name__ == '__main__':
    # TCP socket clint that connects to blueSPY server socket
    sock = blueSPY_socket()
    # byte array to hold HCI bytes
    hci_packet = bytearray()
    # text file parsing (converting to binary bytes) - replace to match your format 
    # text HCI - 2 characters per byte, separated by a space
    with open(filename, 'rb') as file:
        while True:
            str = file.peek(1)
            if len(str) < 1:    # we do not have more data so break
                if len(hci_packet) > 0: # if we have some bytes left; send it
                    sock.send(hci_packet) 
                break
            if chr(str[0]) == byte_sep:
                file.read(1)
                continue
            val = file.read(2)  # read 2 chars = 1 byte
            int_val = int(val, base=16)  # convert the characters to binary
            bytes = int_val.to_bytes(1, byteorder="little")
            for b in bytes:     # add the byte to the array
                hci_packet.append(b)
            # If you have a terminating character for the HCI packet; it may be better to use that
            if len(hci_packet) > 3: # if we have more than 3 bytes send it
                sock.send(hci_packet)
                hci_packet = bytearray()