helper functions for bitwise flag setting

This commit is contained in:
DJ2LS 2023-12-19 14:08:16 +01:00
parent 169990ed58
commit 6a596f1087
2 changed files with 52 additions and 2 deletions

View file

@ -25,6 +25,14 @@ class ARQSession():
}
"""
helpers.set_flag(byte, 'DATA-ACK-NACK', True, FLAG_POSITIONS)
helpers.get_flag(byte, 'DATA-ACK-NACK', FLAG_POSITIONS)
"""
FLAG_POSITIONS = {
'DATA-ACK-NACK': 0, # Bit position for DATA-ACK-NACK
}
def __init__(self, config: dict, modem, dxcall: str):
self.logger = structlog.get_logger(type(self).__name__)
self.config = config
@ -83,4 +91,5 @@ class ARQSession():
return
self.log(f"Ignoring unknow transition from state {self.state} with frame {frame['frame_type']}")

View file

@ -667,4 +667,45 @@ def check_if_file_exists(path):
log.warning(
"[Modem] [FILE] Lookup failed", e=e, path=path,
)
return False
return False
def set_bit(byte, position, value):
"""Set the bit at 'position' to 'value' in the given byte."""
if not 0 <= position <= 7:
raise ValueError("Position must be between 0 and 7")
if value:
return byte | (1 << position)
else:
return byte & ~(1 << position)
def get_bit(byte, position):
"""Get the boolean value of the bit at 'position' in the given byte."""
if not 0 <= position <= 7:
raise ValueError("Position must be between 0 and 7")
return (byte & (1 << position)) != 0
def set_flag(byte, flag_name, value, flag_dict):
"""Set the flag in the byte according to the flag dictionary.
# Define a dictionary mapping flag names to their bit positions
flag_dict = {
'FLAG1': 0, # Bit position for FLAG1
'FLAG2': 1, # Bit position for FLAG2, etc.
'FLAG3': 2
}
"""
if flag_name not in flag_dict:
raise ValueError(f"Unknown flag name: {flag_name}")
position = flag_dict[flag_name]
return set_bit(byte, position, value)
def get_flag(byte, flag_name, flag_dict):
"""Get the value of the flag from the byte according to the flag dictionary."""
if flag_name not in flag_dict:
raise ValueError(f"Unknown flag name: {flag_name}")
position = flag_dict[flag_name]
return get_bit(byte, position)