# (c) Copyright Leonardo S.p.A. and Leonardo MW Ltd. All rights reserved. # Any right of industrial and intellectual property on this document, # and of technical Know-how herein contained, belongs to # Leonardo S.p.a. and Leonardo MW Ltd.and/or third parties. # According to the law, it is forbidden to disclose, reproduce or however # use this document and any data herein contained for any use without # previous written authorization by Leonardo S.p.a. and Leonardo MW Ltd. import socket from typing import Any, AnyStr, List, Tuple class BrainboxInterface: def __init__(self, address, port, _timeout): self.address = address self.port = port self.__client_socket = None self.timeout = _timeout def __connect(self) -> None: if self.__client_socket is not None: return self.__client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.__client_socket.connect((self.address, self.port)) def __disconnect(self) -> None: if self.__client_socket is not None: self.__client_socket.close() self.__client_socket = None def send_data(self, message: str) -> (bool, AnyStr): try: if self.__client_socket is None: self.__connect() self.__client_socket.sendall(message.encode()) except Exception as e: return False, None, f'BrainboxInterface EXCEPTION: {e}' self.__client_socket.settimeout(self.timeout) data_raw = self.__client_socket.recv(1024) data = data_raw.decode() error = None if data[0] == '>': return True, data, error elif data[0] == '?': error = f"BrainboxInterface response {data}: Invalid Command" return False, data, error elif data[0] == '!': error = f"BrainboxInterface response {data}: Ignored Command" return False, data, error error = f"BrainboxInterface response {data}: Unknown Command" return False, data, error if __name__ == "__main__": brainbox_interface = BrainboxInterface('192.168.127.254', 9500, 1) #Query only for relay #01 print(brainbox_interface.send_data('@01\r\n'))