2022-12-15 17:23:54 -05:00
|
|
|
from multiprocessing import RawValue
|
2024-03-23 17:53:01 -04:00
|
|
|
import random
|
2022-12-15 17:23:54 -05:00
|
|
|
import threading
|
|
|
|
|
|
|
|
import wrapt
|
|
|
|
|
|
|
|
|
2024-03-23 17:53:01 -04:00
|
|
|
MAX_PACKET_ID = 9999
|
|
|
|
|
|
|
|
|
2022-12-15 17:23:54 -05:00
|
|
|
class PacketCounter:
|
|
|
|
"""
|
|
|
|
Global Packet id counter class.
|
|
|
|
|
|
|
|
This is a singleton based class that keeps
|
|
|
|
an incrementing counter for all packets to
|
|
|
|
be sent. All new Packet objects gets a new
|
|
|
|
message id, which is the next number available
|
|
|
|
from the PacketCounter.
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
_instance = None
|
|
|
|
lock = threading.Lock()
|
|
|
|
|
|
|
|
def __new__(cls, *args, **kwargs):
|
|
|
|
"""Make this a singleton class."""
|
|
|
|
if cls._instance is None:
|
|
|
|
cls._instance = super().__new__(cls, *args, **kwargs)
|
2024-03-23 17:53:01 -04:00
|
|
|
cls._instance.val = RawValue("i", random.randint(1, MAX_PACKET_ID))
|
2022-12-15 17:23:54 -05:00
|
|
|
return cls._instance
|
|
|
|
|
|
|
|
@wrapt.synchronized(lock)
|
|
|
|
def increment(self):
|
2024-03-23 17:53:01 -04:00
|
|
|
if self.val.value == MAX_PACKET_ID:
|
2022-12-15 17:23:54 -05:00
|
|
|
self.val.value = 1
|
|
|
|
else:
|
|
|
|
self.val.value += 1
|
|
|
|
|
|
|
|
@property
|
|
|
|
@wrapt.synchronized(lock)
|
|
|
|
def value(self):
|
2023-09-29 10:04:15 -04:00
|
|
|
return str(self.val.value)
|
2022-12-15 17:23:54 -05:00
|
|
|
|
|
|
|
@wrapt.synchronized(lock)
|
|
|
|
def __repr__(self):
|
|
|
|
return str(self.val.value)
|
|
|
|
|
|
|
|
@wrapt.synchronized(lock)
|
|
|
|
def __str__(self):
|
|
|
|
return str(self.val.value)
|