85 lines
2.1 KiB
Python
85 lines
2.1 KiB
Python
import threading
|
|
import time
|
|
import random
|
|
|
|
# Shared values
|
|
device_values = [0, 0]
|
|
value_lock = threading.Lock()
|
|
|
|
# Per-device pause controls
|
|
device_events = [threading.Event(), threading.Event()]
|
|
device_events[0].set() # Start as running
|
|
device_events[1].set()
|
|
|
|
# Tolerance threshold
|
|
TOLERANCE = 20
|
|
|
|
# Stop flag
|
|
stop_event = threading.Event()
|
|
|
|
def is_within_tolerance(val_a, val_b):
|
|
return abs(val_a - val_b) <= TOLERANCE
|
|
|
|
# Device thread
|
|
def device_thread(device_id):
|
|
other_id = 1 - device_id
|
|
while not stop_event.is_set():
|
|
device_events[device_id].wait() # Pause if needed
|
|
|
|
# Simulate value from device
|
|
new_value = random.randint(0, 100)
|
|
|
|
with value_lock:
|
|
device_values[device_id] = new_value
|
|
my_val = device_values[device_id]
|
|
other_val = device_values[other_id]
|
|
|
|
print(f"Device {device_id} => {my_val} | Device {other_id} => {other_val}")
|
|
|
|
if not is_within_tolerance(my_val, other_val):
|
|
# print(f"Device {device_id} is out of tolerance! Pausing...")
|
|
# device_events[device_id].clear()
|
|
print("Not within tolerance!")
|
|
|
|
time.sleep(0.1) # Faster check interval
|
|
|
|
# Watcher thread
|
|
def tolerance_watcher():
|
|
while not stop_event.is_set():
|
|
with value_lock:
|
|
val0, val1 = device_values
|
|
if is_within_tolerance(val0, val1):
|
|
for i, event in enumerate(device_events):
|
|
if not event.is_set():
|
|
print(f"Resuming Device {i}")
|
|
event.set()
|
|
|
|
time.sleep(0.05) # Fast response
|
|
|
|
# Start threads
|
|
threads = [
|
|
threading.Thread(target=device_thread, args=(0,)),
|
|
threading.Thread(target=device_thread, args=(1,)),
|
|
threading.Thread(target=tolerance_watcher)
|
|
]
|
|
|
|
for t in threads:
|
|
t.start()
|
|
|
|
# Run loop (press Ctrl+C to stop)
|
|
try:
|
|
while True:
|
|
time.sleep(0.1)
|
|
except KeyboardInterrupt:
|
|
print("Stopping...")
|
|
|
|
stop_event.set()
|
|
for event in device_events:
|
|
event.set()
|
|
|
|
for t in threads:
|
|
t.join()
|
|
|
|
print("All threads stopped.")
|
|
|