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