diff --git a/TrafficCommunication/useful/sharedMem.py b/TrafficCommunication/useful/sharedMem.py index ed7ea51..cd17f71 100755 --- a/TrafficCommunication/useful/sharedMem.py +++ b/TrafficCommunication/useful/sharedMem.py @@ -28,11 +28,14 @@ from multiprocessing import RawArray, Lock import numpy as np +# Default value to indicate an uninitialized field +DEFAULT_VALUE: float = -99.9 + # Define a class for shared memory class sharedMem: def __init__(self, mem_size=20): self.lock = Lock() # Create a lock for thread synchronization - + # Define the shape of the shared memory shared_memory_shape = np.dtype( [ @@ -43,7 +46,7 @@ def __init__(self, mem_size=20): ("finishflag", np.bool_), # Finish flag ] ) - + # Create a raw array for shared memory array = RawArray("c", mem_size * shared_memory_shape.itemsize) shared_memory = np.frombuffer(array, dtype=shared_memory_shape) @@ -57,9 +60,9 @@ def __init__(self, mem_size=20): for mem in self.shared_memory: with self.lock: # Acquire the lock using get_lock() mem["Command"] = "Command_" # Default command string - mem["value1"] = -99.9 # Default value for first value - mem["value2"] = -99.9 # Default value for second value - mem["value3"] = -99.9 # Default value for third value + mem["value1"] = DEFAULT_VALUE + mem["value2"] = DEFAULT_VALUE + mem["value3"] = DEFAULT_VALUE mem["finishflag"] = False # Default finish flag # Method to insert data into shared memory @@ -73,9 +76,9 @@ def insert(self, msg, values): if len(values) > 2: self.shared_memory[self.lastMem]["value3"] = values[2] # Set the third value self.shared_memory[self.lastMem]["finishflag"] = True # Set the finish flag - self.lastMem += 1 # Increment the index of the last memory slot used - if self.lastMem == self.mem_size: - self.lastMem = 0 # Wrap around if the index exceeds the memory size + self.lastMem += 1 # Increment the index of the last memory slot used + if self.lastMem == self.mem_size: + self.lastMem = 0 # Wrap around if the index exceeds the memory size # Method to retrieve data from shared memory def get(self): @@ -84,11 +87,11 @@ def get(self): for mem in self.shared_memory: if mem["finishflag"]: msg = {"reqORinfo": "info", "type": mem["Command"]} # Create a message dictionary - if mem["value1"] != 99.9: + if mem["value1"] != DEFAULT_VALUE: msg["value1"] = float(mem["value1"]) # Add the first value to the message - if mem["value2"] != 99.9: + if mem["value2"] != DEFAULT_VALUE: msg["value2"] = float(mem["value2"]) # Add the second value to the message - if mem["value3"] != 99.9: + if mem["value3"] != DEFAULT_VALUE: msg["value3"] = float(mem["value3"]) # Add the third value to the message mem["finishflag"] = False # Reset the finish flag vals.append(msg) # Append the message to the list of retrieved values