sender.py 2.78 KB
import logging
log = logging.getLogger(__name__)
class ISO8583Sender:
    def __init__(self, response_queue, sender_lock, mpp_connections):
        self.response_queue = response_queue
        self.sender_lock = sender_lock
        self.mpp_connections = mpp_connections

    def start(self):
        count = 0
        # print(f"[SENDER INIT] mpp_connections type: {type(self.mpp_connections)}, value: {self.mpp_connections}")
        if self.mpp_connections is None:
            raise RuntimeError("mpp_connections is None in sender process. Ensure init_mpp() is called in main process before starting sender.")
        while True:
            
            filename, response = self.response_queue.get()
            conn_name = filename.rsplit('_', 3)[0]
            with self.sender_lock:
                count += 1
                # print(f"[SENDER DEBUG] Got from queue: filename={filename}")
                # print(f"[SENDER] mpp_connections keys: {list(self.mpp_connections.keys())}")
                item = self.mpp_connections.get(conn_name)
                if not item or not item.get("running", False):
                    # print(f"[SENDER] No connection for {conn_name}, skipping.")
                    continue
                # Wait for client_sock to be set, retry if None
                retries = 0
                while True:
                    sock = item.get('client_sock')
                    # print(f"[SENDER] client_sock for {conn_name}: {sock}")
                    if sock:
                        break
                    retries += 1
                    if retries > 10:
                        # print(f"[SENDER] No client socket for {conn_name} after {retries} retries, skipping.")
                        break
                    import time
                    time.sleep(0.2)
                if not sock:
                    continue
                etx = item.get('etx', False)
                response_data = response
                if etx and not response_data.endswith(b'\x03'):
                    response_data += b'\x03'
                frame_len = len(response_data)
                length = str(frame_len).zfill(4).encode('ascii')
                new_data = length + response_data
                try:
                    sock.sendall(new_data)
                    log.info(f"[SENDER] Sending response to {conn_name}: {response_data}, frame_len={frame_len}, count={count}")
                except Exception as send_err:
                    log.error(f"[SENDER ERROR] sendall failed for {conn_name}: {send_err}")
            # except Exception as send_err:
            #     print(f"[SENDER ERROR] sendall failed for {conn_name}: {send_err}")

    # def start(self, interval=0.5):
    #     import time
    #     while True:
    #         self.send_responses()
    #         time.sleep(interval)