11import time
2+ import logging
23import os
34from ast import literal_eval
45import sys
56import re
6- import zmq # Added for ZeroMQ
7- import numpy as np # Added for numpy type conversion
7+ import zmq
8+ logging .basicConfig (
9+ level = logging .INFO ,
10+ format = '%(levelname)s - %(message)s'
11+ ) # Added for ZeroMQ
812
913# if windows, create script to kill this process
1014# because batch files don't provide easy way to know pid of last command
@@ -37,10 +41,10 @@ def __init__(self, port_type, address, zmq_socket_type):
3741 # Bind or connect
3842 if self .port_type == "bind" :
3943 self .socket .bind (address )
40- print (f"ZMQ Port bound to { address } " )
44+ logging . info (f"ZMQ Port bound to { address } " )
4145 else :
4246 self .socket .connect (address )
43- print (f"ZMQ Port connected to { address } " )
47+ logging . info (f"ZMQ Port connected to { address } " )
4448
4549 def send_json_with_retry (self , message ):
4650 """Send JSON message with retries if timeout occurs."""
@@ -49,9 +53,9 @@ def send_json_with_retry(self, message):
4953 self .socket .send_json (message )
5054 return
5155 except zmq .Again :
52- print (f"Send timeout (attempt { attempt + 1 } /5)" )
56+ logging . warning (f"Send timeout (attempt { attempt + 1 } /5)" )
5357 time .sleep (0.5 )
54- print ("Failed to send after retries." )
58+ logging . error ("Failed to send after retries." )
5559 return
5660
5761 def recv_json_with_retry (self ):
@@ -60,9 +64,9 @@ def recv_json_with_retry(self):
6064 try :
6165 return self .socket .recv_json ()
6266 except zmq .Again :
63- print (f"Receive timeout (attempt { attempt + 1 } /5)" )
67+ logging . warning (f"Receive timeout (attempt { attempt + 1 } /5)" )
6468 time .sleep (0.5 )
65- print ("Failed to receive after retries." )
69+ logging . error ("Failed to receive after retries." )
6670 return None
6771
6872# Global ZeroMQ ports registry
@@ -77,28 +81,28 @@ def init_zmq_port(port_name, port_type, address, socket_type_str):
7781 socket_type_str (str): String representation of ZMQ socket type (e.g., "REQ", "REP", "PUB", "SUB").
7882 """
7983 if port_name in zmq_ports :
80- print (f"ZMQ Port { port_name } already initialized." )
84+ logging . info (f"ZMQ Port { port_name } already initialized." )
8185 return # Avoid reinitialization
8286
8387 try :
8488 # Map socket type string to actual ZMQ constant (e.g., zmq.REQ, zmq.REP)
8589 zmq_socket_type = getattr (zmq , socket_type_str .upper ())
8690 zmq_ports [port_name ] = ZeroMQPort (port_type , address , zmq_socket_type )
87- 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 } " )
8892 except AttributeError :
89- print (f"Error: Invalid ZMQ socket type string '{ socket_type_str } '." )
93+ logging . error (f"Error: Invalid ZMQ socket type string '{ socket_type_str } '." )
9094 except zmq .error .ZMQError as e :
91- print (f"Error initializing ZMQ port { port_name } on { address } : { e } " )
95+ logging . error (f"Error initializing ZMQ port { port_name } on { address } : { e } " )
9296 except Exception as e :
93- 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 } " )
9498
9599def terminate_zmq ():
96100 for port in zmq_ports .values ():
97101 try :
98102 port .socket .close ()
99103 port .context .term ()
100104 except Exception as e :
101- print (f"Error while terminating ZMQ port { port .address } : { e } " )
105+ logging . error (f"Error while terminating ZMQ port { port .address } : { e } " )
102106# --- ZeroMQ Integration End ---
103107
104108
@@ -163,13 +167,13 @@ def safe_literal_eval(filename, defaultValue):
163167
164168 # Convert key=value;key2=value2 to Python dict format
165169 if sparams != '{' and not (sparams .startswith ('{' ) and sparams .endswith ('}' )): # Check if it needs conversion
166- print ("converting sparams: " + sparams )
170+ logging . debug ("converting sparams: " + sparams )
167171 sparams = "{'" + re .sub (';' ,",'" ,re .sub ('=' ,"':" ,re .sub (' ' ,'' ,sparams )))+ "}"
168- print ("converted sparams: " + sparams )
172+ logging . debug ("converted sparams: " + sparams )
169173 try :
170174 params = literal_eval (sparams )
171175 except Exception as e :
172- print (f"bad params content: { sparams } , error: { e } " )
176+ logging . warning (f"bad params content: { sparams } , error: { e } " )
173177 params = dict ()
174178 else :
175179 params = dict ()
@@ -226,17 +230,17 @@ def read(port_identifier, name, initstr_val):
226230 message = zmq_p .recv_json_with_retry ()
227231 return message
228232 except zmq .error .ZMQError as e :
229- print (f"ZMQ read error on port { port_identifier } (name: { name } ): { e } . Returning default." )
233+ logging . error (f"ZMQ read error on port { port_identifier } (name: { name } ): { e } . Returning default." )
230234 return default_return_val
231235 except Exception as e :
232- print (f"Unexpected error during ZMQ read on port { port_identifier } (name: { name } ): { e } . Returning default." )
236+ logging . error (f"Unexpected error during ZMQ read on port { port_identifier } (name: { name } ): { e } . Returning default." )
233237 return default_return_val
234238
235239 # Case 2: File-based port
236240 try :
237241 file_port_num = int (port_identifier )
238242 except ValueError :
239- print (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
243+ logging . error (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
240244 return default_return_val
241245
242246 time .sleep (delay )
@@ -250,8 +254,7 @@ def read(port_identifier, name, initstr_val):
250254 ins = str (initstr_val )
251255 s += ins # Update s to break unchanged() loop
252256 except Exception as e :
253- print (f"Error reading { file_path } : { e } . Using default value." )
254- s += str (initstr_val ) # Update s to break unchanged() loop
257+ logging .error (f"Error reading { file_path } : { e } . Using default value." )
255258 return default_return_val
256259
257260 # Retry logic if file is empty
@@ -263,13 +266,12 @@ def read(port_identifier, name, initstr_val):
263266 with open (file_path , "r" ) as infile :
264267 ins = infile .read ()
265268 except Exception as e :
266- print (f"Retry { attempts + 1 } : Error reading { file_path } - { e } " )
269+ logging . warning (f"Retry { attempts + 1 } : Error reading { file_path } - { e } " )
267270 attempts += 1
268271 retrycount += 1
269272
270273 if len (ins ) == 0 :
271- print (f"Max retries reached for { file_path } , using default value." )
272- s += str (initstr_val ) # Update s to break unchanged() loop
274+ logging .error (f"Max retries reached for { file_path } , using default value." )
273275 return default_return_val
274276
275277 s += ins
@@ -283,10 +285,10 @@ def read(port_identifier, name, initstr_val):
283285 simtime = max (simtime , current_simtime_from_file )
284286 return inval [1 :]
285287 else :
286- print (f"Warning: Unexpected data format in { file_path } : { ins } . Returning raw content or default." )
288+ logging . warning (f"Warning: Unexpected data format in { file_path } : { ins } . Returning raw content or default." )
287289 return inval
288290 except Exception as e :
289- print (f"Error parsing content from { file_path } ('{ ins } '): { e } . Returning default." )
291+ logging . error (f"Error parsing content from { file_path } ('{ ins } '): { e } . Returning default." )
290292 return default_return_val
291293
292294
@@ -303,24 +305,23 @@ def write(port_identifier, name, val, delta=0):
303305 try :
304306 zmq_p .send_json_with_retry (val )
305307 except zmq .error .ZMQError as e :
306- print (f"ZMQ write error on port { port_identifier } (name: { name } ): { e } " )
308+ logging . error (f"ZMQ write error on port { port_identifier } (name: { name } ): { e } " )
307309 except Exception as e :
308- print (f"Unexpected error during ZMQ write on port { port_identifier } (name: { name } ): { e } " )
309- return
310+ logging .error (f"Unexpected error during ZMQ write on port { port_identifier } (name: { name } ): { e } " )
310311
311312 # Case 2: File-based port
312313 try :
313314 file_port_num = int (port_identifier )
314315 file_path = os .path .join (outpath + str (file_port_num ), name )
315316 except ValueError :
316- print (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
317+ logging . error (f"Error: Invalid port identifier '{ port_identifier } ' for file operation. Must be integer or ZMQ name." )
317318 return
318319
319320 # File writing rules
320321 if isinstance (val , str ):
321322 time .sleep (2 * delay ) # string writes wait longer
322323 elif not isinstance (val , list ):
323- print (f"File write to { file_path } must have list or str value, got { type (val )} " )
324+ logging . error (f"File write to { file_path } must have list or str value, got { type (val )} " )
324325 return
325326
326327 try :
@@ -334,7 +335,7 @@ def write(port_identifier, name, val, delta=0):
334335 else :
335336 outfile .write (val )
336337 except Exception as e :
337- print (f"Error writing to { file_path } : { e } " )
338+ logging . error (f"Error writing to { file_path } : { e } " )
338339
339340def initval (simtime_val_str ):
340341 """
@@ -350,12 +351,12 @@ def initval(simtime_val_str):
350351 simtime = first_element
351352 return val [1 :]
352353 else :
353- print (f"Error: First element in initval string '{ simtime_val_str } ' is not a number. Using data part as is or empty." )
354+ logging . error (f"Error: First element in initval string '{ simtime_val_str } ' is not a number. Using data part as is or empty." )
354355 return val [1 :] if len (val ) > 1 else []
355356 else :
356- print (f"Error: initval string '{ simtime_val_str } ' is not a list or is empty. Returning empty list." )
357+ logging . error (f"Error: initval string '{ simtime_val_str } ' is not a list or is empty. Returning empty list." )
357358 return []
358359
359360 except Exception as e :
360- print (f"Error parsing simtime_val_str '{ simtime_val_str } ': { e } . Returning empty list." )
361+ logging . error (f"Error parsing simtime_val_str '{ simtime_val_str } ': { e } . Returning empty list." )
361362 return []
0 commit comments