11import time
2+ import logging
23import os
34from ast import literal_eval
45import sys
56import re
6- import zmq # Added for ZeroMQ
7+ import zmq
8+ logging .basicConfig (
9+ level = logging .INFO ,
10+ format = '%(levelname)s - %(message)s'
11+ ) # Added for ZeroMQ
712
813# if windows, create script to kill this process
914# because batch files don't provide easy way to know pid of last command
@@ -36,10 +41,10 @@ def __init__(self, port_type, address, zmq_socket_type):
3641 # Bind or connect
3742 if self .port_type == "bind" :
3843 self .socket .bind (address )
39- print (f"ZMQ Port bound to { address } " )
44+ logging . info (f"ZMQ Port bound to { address } " )
4045 else :
4146 self .socket .connect (address )
42- print (f"ZMQ Port connected to { address } " )
47+ logging . info (f"ZMQ Port connected to { address } " )
4348
4449 def send_json_with_retry (self , message ):
4550 """Send JSON message with retries if timeout occurs."""
@@ -48,9 +53,9 @@ def send_json_with_retry(self, message):
4853 self .socket .send_json (message )
4954 return
5055 except zmq .Again :
51- print (f"Send timeout (attempt { attempt + 1 } /5)" )
56+ logging . warning (f"Send timeout (attempt { attempt + 1 } /5)" )
5257 time .sleep (0.5 )
53- print ("Failed to send after retries." )
58+ logging . error ("Failed to send after retries." )
5459 return
5560
5661 def recv_json_with_retry (self ):
@@ -59,9 +64,9 @@ def recv_json_with_retry(self):
5964 try :
6065 return self .socket .recv_json ()
6166 except zmq .Again :
62- print (f"Receive timeout (attempt { attempt + 1 } /5)" )
67+ logging . warning (f"Receive timeout (attempt { attempt + 1 } /5)" )
6368 time .sleep (0.5 )
64- print ("Failed to receive after retries." )
69+ logging . error ("Failed to receive after retries." )
6570 return None
6671
6772# Global ZeroMQ ports registry
@@ -76,28 +81,28 @@ def init_zmq_port(port_name, port_type, address, socket_type_str):
7681 socket_type_str (str): String representation of ZMQ socket type (e.g., "REQ", "REP", "PUB", "SUB").
7782 """
7883 if port_name in zmq_ports :
79- print (f"ZMQ Port { port_name } already initialized." )
84+ logging . info (f"ZMQ Port { port_name } already initialized." )
8085 return # Avoid reinitialization
8186
8287 try :
8388 # Map socket type string to actual ZMQ constant (e.g., zmq.REQ, zmq.REP)
8489 zmq_socket_type = getattr (zmq , socket_type_str .upper ())
8590 zmq_ports [port_name ] = ZeroMQPort (port_type , address , zmq_socket_type )
86- print (f"Initialized ZMQ port: { port_name } ({ socket_type_str } ) on { address } " )
91+ logging . info (f"Initialized ZMQ port: { port_name } ({ socket_type_str } ) on { address } " )
8792 except AttributeError :
88- print (f"Error: Invalid ZMQ socket type string '{ socket_type_str } '." )
93+ logging . error (f"Error: Invalid ZMQ socket type string '{ socket_type_str } '." )
8994 except zmq .error .ZMQError as e :
90- print (f"Error initializing ZMQ port { port_name } on { address } : { e } " )
95+ logging . error (f"Error initializing ZMQ port { port_name } on { address } : { e } " )
9196 except Exception as e :
92- print (f"An unexpected error occurred during ZMQ port initialization for { port_name } : { e } " )
97+ logging . error (f"An unexpected error occurred during ZMQ port initialization for { port_name } : { e } " )
9398
9499def terminate_zmq ():
95100 for port in zmq_ports .values ():
96101 try :
97102 port .socket .close ()
98103 port .context .term ()
99104 except Exception as e :
100- print (f"Error while terminating ZMQ port { port .address } : { e } " )
105+ logging . error (f"Error while terminating ZMQ port { port .address } : { e } " )
101106# --- ZeroMQ Integration End ---
102107
103108# ===================================================================
@@ -142,13 +147,13 @@ def safe_literal_eval(filename, defaultValue):
142147
143148 # Convert key=value;key2=value2 to Python dict format
144149 if sparams != '{' and not (sparams .startswith ('{' ) and sparams .endswith ('}' )): # Check if it needs conversion
145- print ("converting sparams: " + sparams )
150+ logging . debug ("converting sparams: " + sparams )
146151 sparams = "{'" + re .sub (';' ,",'" ,re .sub ('=' ,"':" ,re .sub (' ' ,'' ,sparams )))+ "}"
147- print ("converted sparams: " + sparams )
152+ logging . debug ("converted sparams: " + sparams )
148153 try :
149154 params = literal_eval (sparams )
150155 except Exception as e :
151- print (f"bad params content: { sparams } , error: { e } " )
156+ logging . warning (f"bad params content: { sparams } , error: { e } " )
152157 params = dict ()
153158 else :
154159 params = dict ()
@@ -206,17 +211,17 @@ def read(port_identifier, name, initstr_val):
206211 message = zmq_p .recv_json_with_retry ()
207212 return message
208213 except zmq .error .ZMQError as e :
209- print (f"ZMQ read error on port { port_identifier } (name: { name } ): { e } . Returning default." )
214+ logging . error (f"ZMQ read error on port { port_identifier } (name: { name } ): { e } . Returning default." )
210215 return default_return_val
211216 except Exception as e :
212- print (f"Unexpected error during ZMQ read on port { port_identifier } (name: { name } ): { e } . Returning default." )
217+ logging . error (f"Unexpected error during ZMQ read on port { port_identifier } (name: { name } ): { e } . Returning default." )
213218 return default_return_val
214219
215220 # Case 2: File-based port
216221 try :
217222 file_port_num = int (port_identifier )
218223 except ValueError :
219- print (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
224+ logging . error (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
220225 return default_return_val
221226
222227 time .sleep (delay )
@@ -229,7 +234,7 @@ def read(port_identifier, name, initstr_val):
229234 except FileNotFoundError :
230235 ins = str (initstr_val )
231236 except Exception as e :
232- print (f"Error reading { file_path } : { e } . Using default value." )
237+ logging . error (f"Error reading { file_path } : { e } . Using default value." )
233238 return default_return_val
234239
235240 # Retry logic if file is empty
@@ -241,12 +246,12 @@ def read(port_identifier, name, initstr_val):
241246 with open (file_path , "r" ) as infile :
242247 ins = infile .read ()
243248 except Exception as e :
244- print (f"Retry { attempts + 1 } : Error reading { file_path } - { e } " )
249+ logging . warning (f"Retry { attempts + 1 } : Error reading { file_path } - { e } " )
245250 attempts += 1
246251 retrycount += 1
247252
248253 if len (ins ) == 0 :
249- print (f"Max retries reached for { file_path } , using default value." )
254+ logging . error (f"Max retries reached for { file_path } , using default value." )
250255 return default_return_val
251256
252257 s += ins
@@ -260,10 +265,10 @@ def read(port_identifier, name, initstr_val):
260265 simtime = max (simtime , current_simtime_from_file )
261266 return inval [1 :]
262267 else :
263- print (f"Warning: Unexpected data format in { file_path } : { ins } . Returning raw content or default." )
268+ logging . warning (f"Warning: Unexpected data format in { file_path } : { ins } . Returning raw content or default." )
264269 return inval
265270 except Exception as e :
266- print (f"Error parsing content from { file_path } ('{ ins } '): { e } . Returning default." )
271+ logging . error (f"Error parsing content from { file_path } ('{ ins } '): { e } . Returning default." )
267272 return default_return_val
268273
269274
@@ -280,9 +285,9 @@ def write(port_identifier, name, val, delta=0):
280285 try :
281286 zmq_p .send_json_with_retry (val )
282287 except zmq .error .ZMQError as e :
283- print (f"ZMQ write error on port { port_identifier } (name: { name } ): { e } " )
288+ logging . error (f"ZMQ write error on port { port_identifier } (name: { name } ): { e } " )
284289 except Exception as e :
285- print (f"Unexpected error during ZMQ write on port { port_identifier } (name: { name } ): { e } " )
290+ logging . error (f"Unexpected error during ZMQ write on port { port_identifier } (name: { name } ): { e } " )
286291
287292 # Case 2: File-based port
288293 try :
@@ -292,14 +297,14 @@ def write(port_identifier, name, val, delta=0):
292297 file_port_num = int (port_identifier )
293298 file_path = os .path .join (outpath + str (file_port_num ), name )
294299 except ValueError :
295- print (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
300+ logging . error (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
296301 return
297302
298303 # File writing rules
299304 if isinstance (val , str ):
300305 time .sleep (2 * delay ) # string writes wait longer
301306 elif not isinstance (val , list ):
302- print (f"File write to { file_path } must have list or str value, got { type (val )} " )
307+ logging . error (f"File write to { file_path } must have list or str value, got { type (val )} " )
303308 return
304309
305310 try :
@@ -311,7 +316,7 @@ def write(port_identifier, name, val, delta=0):
311316 else :
312317 outfile .write (val )
313318 except Exception as e :
314- print (f"Error writing to { file_path } : { e } " )
319+ logging . error (f"Error writing to { file_path } : { e } " )
315320
316321def initval (simtime_val_str ):
317322 """
@@ -327,12 +332,12 @@ def initval(simtime_val_str):
327332 simtime = first_element
328333 return val [1 :]
329334 else :
330- print (f"Error: First element in initval string '{ simtime_val_str } ' is not a number. Using data part as is or empty." )
335+ logging . error (f"Error: First element in initval string '{ simtime_val_str } ' is not a number. Using data part as is or empty." )
331336 return val [1 :] if len (val ) > 1 else []
332337 else :
333- print (f"Error: initval string '{ simtime_val_str } ' is not a list or is empty. Returning empty list." )
338+ logging . error (f"Error: initval string '{ simtime_val_str } ' is not a list or is empty. Returning empty list." )
334339 return []
335340
336341 except Exception as e :
337- print (f"Error parsing simtime_val_str '{ simtime_val_str } ': { e } . Returning empty list." )
342+ logging . error (f"Error parsing simtime_val_str '{ simtime_val_str } ': { e } . Returning empty list." )
338343 return []
0 commit comments