-2

Can someone help me. I'm looking for an example of a python function that avoids sending many alarm messages if a transition from true to false of a variable is repeated many times by setting a maximum number of transitions. Thank you.

I hope to find a solution

horus61
  • 1
  • 1
  • This Q/A: [How to trigger function on value change?](https://stackoverflow.com/questions/6190468/how-to-trigger-function-on-value-change) can help. You can add a counter which will stop sending alarm messages when it is counted _many times_. – Luuk Aug 28 '23 at 16:55

1 Answers1

-1

To achieve your goal of avoiding sending too many alarm messages when a variable toggles between True and False frequently, you can implement a debounce mechanism. A debounce mechanism will delay the alarm message until a certain period of stability has been reached for the variable. Here's an example Python function that demonstrates this concept:

import time

class Debouncer:
    def __init__(self, max_transitions, debounce_time):
        self.max_transitions = max_transitions
        self.debounce_time = debounce_time
        self.transition_count = 0
        self.last_transition_time = time.time()

def check_transition(self, new_state):
    current_time = time.time()
    
    if new_state != self.current_state:
        self.transition_count += 1
        self.last_transition_time = current_time
        self.current_state = new_state
        
        if self.transition_count >= self.max_transitions:
            if current_time - self.last_transition_time >= self.debounce_time:
                self.transition_count = 0
                self.last_transition_time = current_time
                return True
            
    elif self.transition_count > 0 and current_time - self.last_transition_time >= self.debounce_time:
        self.transition_count = 0
        self.last_transition_time = current_time
        return True
    
    return False

   def simulate_variable_changes():
        variable = False
        debouncer = Debouncer(max_transitions=3, debounce_time=1.0)   

while True:
    variable = not variable
    
    if debouncer.check_transition(variable):
        print("Sending alarm message!")
    
    time.sleep(0.5)  # Simulate a delay between transitions

simulate_variable_changes()
guirms
  • 49
  • 7