import socket import time import random from datetime import datetime HOST = "127.0.0.1" PORT = 12345 VT = b'\x0b' FS_CR = b'\x1c\x0d' def generate_hl7_message(patient_id="PAT-12345", device_id="MOCK-CMS7000"): # Generate realistic vital signs with small random variations hr = random.randint(70, 95) spo2 = random.randint(96, 99) sys = random.randint(115, 125) dia = random.randint(75, 83) map_bp = int(dia + (sys - dia) / 3) resp = random.randint(14, 18) temp = round(random.uniform(36.5, 37.1), 1) now_str = datetime.now().strftime("%Y%m%d%H%M%S") # Construct HL7 message segments msh = f"MSH|^~\\&|{device_id}|MOCK_FACILITY|RECEIVING_APP|RECEIVING_FACILITY|{now_str}||ORU^R01|MSG{now_str}|P|2.3.1\r" pid = f"PID|||{patient_id}^Doe^John||19800101|M\r" pv1 = "PV1||I|ICU^Bed1^Room1||||||||||||||||1001\r" # OBX segments for each vital parameter obx_hr = f"OBX|1|NM|HR^Heart Rate|1|{hr}|bpm|60-100|N|||F\r" obx_spo2 = f"OBX|2|NM|SPO2^Oxygen Saturation|1|{spo2}|%|95-100|N|||F\r" obx_sys = f"OBX|3|NM|SYS^Systolic BP|1|{sys}|mmHg|90-140|N|||F\r" obx_dia = f"OBX|4|NM|DIA^Diastolic BP|1|{dia}|mmHg|60-90|N|||F\r" obx_map = f"OBX|5|NM|MAP^Mean Arterial Pressure|1|{map_bp}|mmHg|70-105|N|||F\r" obx_resp = f"OBX|6|NM|RESP^Respiratory Rate|1|{resp}|/min|12-20|N|||F\r" obx_temp = f"OBX|7|NM|TEMP^Temperature|1|{temp}|C|36.1-37.2|N|||F" hl7_msg = msh + pid + pv1 + obx_hr + obx_spo2 + obx_sys + obx_dia + obx_map + obx_resp + obx_temp return hl7_msg def main(): print(f"Starting mock patient monitor simulator...") print(f"Connecting to Contec receiver at {HOST}:{PORT}...") while True: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) print(f"Connected to Contec server at {HOST}:{PORT}") while True: hl7_msg = generate_hl7_message() # Frame message with MLLP wrappers (VT ... FS_CR) framed_msg = VT + hl7_msg.encode('utf-8') + FS_CR print(f"[{datetime.now().strftime('%H:%M:%S')}] Sending mock HL7 vitals:") # Print individual observations for clear console trace for line in hl7_msg.split('\r'): if line.startswith("OBX"): print(f" {line}") s.sendall(framed_msg) # Check for ACK response try: s.settimeout(1.0) response = s.recv(4096) if response: print(" [ACK Received]") except socket.timeout: pass time.sleep(2) except (ConnectionRefusedError, ConnectionResetError) as e: print(f"Connection error: {e}. Retrying in 3 seconds...") time.sleep(3) except Exception as e: print(f"Unexpected error: {e}. Retrying in 3 seconds...") time.sleep(3) if __name__ == "__main__": main()