1from __future__ import absolute_import 2 3from builtins import bytes 4from builtins import object 5 6import logging 7import socket 8import select 9 10class Interface(object): 11 """Basic communication interface.""" 12 def __init__(self, host_cfg, portnum): 13 super(Interface, self).__init__() 14 self.host_cfg = host_cfg 15 self.portnum = portnum 16 self.pkt_size = 8192 17 self.socket = None 18 self.isblocking = True 19 logging.debug("created %s" % str(self)) 20 21 def connect(self): 22 self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 23 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 24 self.socket.bind((self.host_cfg, self.portnum)) 25 logging.debug("Initializing network interface for communication host: %s:%d", self.host_cfg, self.portnum) 26 self.socket.listen(5) 27 num_retries = 3 28 while num_retries > 0: 29 ra,wa,ea = select.select([self.socket], [], [], 30) 30 if not ra: 31 num_retries -= 1 32 logging.warning("timeout: select returned empty list. retrying..") 33 continue 34 self.connection, addr = self.socket.accept() 35 logging.info("Connected to client from %s" % str(addr)) 36 return True 37 logging.error("Failed to connect. Exiting after multiple attempts.") 38 return False 39 40 def read(self): 41 if self.isblocking: 42 #BUG TODO make this unblocking soon 43 #logging.warn("blocking read bug") 44 self.connection.settimeout(15) 45 self.isblocking = False 46 r_bytes = bytes() 47 try: 48 r_bytes = self.connection.recv(self.pkt_size) 49 except Exception as e: 50 #logging.debug("Found exception in recv. %s " % (str(e))) 51 pass 52 53 return r_bytes 54 55 def write(self, str): 56 if not self.isblocking: 57 self.connection.setblocking(1) 58 self.isblocking = True 59 return self.connection.send(str.encode()) 60 61 def close(self): 62 if self.connection: 63 logging.debug('closing connection.') 64 self.connection.close() 65 return self.socket 66 67 def __str__(self): 68 return "interface: %s %d" % (self.host_cfg, self.portnum) 69