from machine import ADC, Pin, PWM
import time
from event_queue import (
create_event,
enqueue_event,
dequeue_event,
record_processed_event,
get_queue_size,
get_event_statistics
)
from priority_queue import (
create_priority_event,
enqueue_priority_event,
dequeue_priority_event,
get_priority_queue_size,
get_priority_statistics
)
# ==========================================
# 1. Hardware Initialization
# ==========================================
pot = ADC(26)
mode_switch = Pin(14, Pin.IN, Pin.PULL_DOWN)
emergency_button = Pin(15, Pin.IN, Pin.PULL_UP)
green_pwm = PWM(Pin(16))
green_pwm.freq(1000)
red_led = Pin(17, Pin.OUT)
buzzer_pwm = PWM(Pin(18))
buzzer_pwm.freq(1000)
green_pwm.duty_u16(0)
red_led.value(0)
buzzer_pwm.duty_u16(0)
# ==========================================
# 2. System Configuration
# ==========================================
LOOP_INTERVAL_MS = 50
DEBOUNCE_MS = 30
RECOVERY_DURATION_MS = 3000
MONITOR_INTERVAL_MS = 500
CRITICAL_THRESHOLD = 80
LOAD_LEVELS = {
"LOW": 20,
"MEDIUM": 50,
"HIGH": 75,
"CRITICAL": 100
}
# ==========================================
# 3. State Management
# ==========================================
NORMAL = "NORMAL"
PRIORITY_PROTECTION = "PRIORITY_PROTECTION"
RECOVERY = "RECOVERY"
current_state = NORMAL
recovery_start = 0
# ==========================================
# 4. Button Debouncing
# ==========================================
raw_button_state = emergency_button.value()
stable_button_state = raw_button_state
last_change_time = time.ticks_ms()
def read_debounced_button():
global raw_button_state
global stable_button_state
global last_change_time
current_reading = emergency_button.value()
now = time.ticks_ms()
if current_reading != raw_button_state:
raw_button_state = current_reading
last_change_time = now
if time.ticks_diff(now, last_change_time) >= DEBOUNCE_MS:
if stable_button_state != raw_button_state:
stable_button_state = raw_button_state
if stable_button_state == 0:
print("Debounced: BUTTON PRESSED")
else:
print("Debounced: BUTTON RELEASED")
return stable_button_state == 0
# ==========================================
# 5. Load Reading and Classification
# ==========================================
def read_load():
adc_value = pot.read_u16()
load = adc_value / 65535 * 100
return load, adc_value
def classify_load(load):
if load <= 30:
return "LOW"
elif load <= 60:
return "MEDIUM"
elif load <= 80:
return "HIGH"
else:
return "CRITICAL"
# ==========================================
# 6. State Transition
# ==========================================
def update_state(button_pressed, load):
global current_state
global recovery_start
now = time.ticks_ms()
if current_state == NORMAL:
if button_pressed or load > CRITICAL_THRESHOLD:
current_state = PRIORITY_PROTECTION
elif current_state == PRIORITY_PROTECTION:
if not button_pressed and load <= CRITICAL_THRESHOLD:
current_state = RECOVERY
recovery_start = now
elif current_state == RECOVERY:
if button_pressed or load > CRITICAL_THRESHOLD:
current_state = PRIORITY_PROTECTION
elif time.ticks_diff(
now, recovery_start
) >= RECOVERY_DURATION_MS:
current_state = NORMAL
return current_state
# ==========================================
# 7. PWM Output Control
# ==========================================
def set_green_led(load_level):
duty_percent = LOAD_LEVELS[load_level]
duty_value = int(65535 * duty_percent / 100)
green_pwm.duty_u16(duty_value)
def update_outputs(state, load_level):
if state == NORMAL:
set_green_led(load_level)
red_led.value(0)
buzzer_pwm.duty_u16(0)
elif state == PRIORITY_PROTECTION:
green_pwm.duty_u16(0)
red_led.value(1)
buzzer_pwm.duty_u16(32768)
elif state == RECOVERY:
set_green_led(load_level)
red_led.value(0)
buzzer_pwm.duty_u16(0)
# ==========================================
# 8. Event Processing
# ==========================================
# Stores the timestamp of a protection-triggering
# event detected during the current scheduler cycle.
cycle_protection_timestamp = None
def process_priority_events():
global cycle_protection_timestamp
while get_priority_queue_size() > 0:
event = dequeue_priority_event()
event_type = event["type"]
if event_type == "EMERGENCY_PRESSED":
if cycle_protection_timestamp is None:
cycle_protection_timestamp = event["timestamp"]
elif event_type == "CRITICAL_LOAD_DETECTED":
if cycle_protection_timestamp is None:
cycle_protection_timestamp = event["timestamp"]
if mode_switch.value() == 1:
print("[Priority Event]", event_type)
def process_normal_event():
global max_queue_wait_ms
event = dequeue_event()
if event is None:
return
now = time.ticks_ms()
wait_time = time.ticks_diff(
now, event["timestamp"]
)
if wait_time > max_queue_wait_ms:
max_queue_wait_ms = wait_time
event_type = event["type"]
if event_type == "LOAD_LEVEL_CHANGED":
print("Normal Event: Load Level Changed ->",
event["value"])
elif event_type == "PROFILE_CHANGED":
if event["value"] == 0:
print("Monitoring Profile: STANDARD")
else:
print("Monitoring Profile: ENHANCED")
elif event_type == "RECOVERY_COMPLETED":
print("Normal Event: Recovery Completed")
elif event_type == "SYSTEM_DIAGNOSTIC":
print("Normal Event: System Diagnostic")
record_processed_event()
# ==========================================
# 9. Monitoring and Performance Statistics
# ==========================================
def display_monitoring(load, adc_value, load_level, state):
profile = mode_switch.value()
if profile == 0:
print(
"Load:", round(load, 1), "%",
"| Level:", load_level,
"| State:", state
)
else:
print(
"[Enhanced]",
"Load:", round(load, 1), "%",
"| ADC:", adc_value,
"| Level:", load_level,
"| State:", state
)
print("Normal Queue:", get_event_statistics())
print("Priority Queue:", get_priority_statistics())
print("Maximum Queue Wait:", max_queue_wait_ms, "ms")
print("Maximum Protection Response:",
max_protection_response_ms, "ms")
max_queue_wait_ms = 0
max_protection_response_ms = 0
scheduler_overruns = 0
max_cycle_execution_ms = 0
# ==========================================
# 10. Input Processing
# ==========================================
previous_button_pressed = stable_button_state == 0
previous_critical = False
previous_load_level = None
previous_profile = mode_switch.value()
def process_inputs(load, load_level, button_pressed):
global previous_button_pressed
global previous_critical
global previous_load_level
global previous_profile
# --------------------------------------
# A. Emergency Button Events
# --------------------------------------
if button_pressed != previous_button_pressed:
if button_pressed:
event = create_priority_event(
"EMERGENCY_PRESSED"
)
else:
event = create_priority_event(
"EMERGENCY_RELEASED"
)
# Use the original raw input-change time.
event["timestamp"] = last_change_time
enqueue_priority_event(event)
previous_button_pressed = button_pressed
# --------------------------------------
# B. Critical Load Events
# --------------------------------------
critical_now = load > CRITICAL_THRESHOLD
if critical_now and not previous_critical:
event = create_priority_event(
"CRITICAL_LOAD_DETECTED",
round(load, 1)
)
enqueue_priority_event(event)
previous_critical = critical_now
# --------------------------------------
# C. Load Level Changes
# --------------------------------------
if load_level != previous_load_level:
event = create_event(
"LOAD_LEVEL_CHANGED",
load_level
)
enqueue_event(event)
previous_load_level = load_level
# --------------------------------------
# D. Monitoring Profile Changes
# --------------------------------------
current_profile = mode_switch.value()
if current_profile != previous_profile:
event = create_event(
"PROFILE_CHANGED",
current_profile
)
enqueue_event(event)
previous_profile = current_profile
# ==========================================
# 11. Scheduler Cycle
# ==========================================
last_monitor_time = time.ticks_ms()
def scheduler_cycle():
global cycle_protection_timestamp
global max_protection_response_ms
global last_monitor_time
global scheduler_overruns
global max_cycle_execution_ms
cycle_start = time.ticks_ms()
# Step 1: Read inputs
load, adc_value = read_load()
button_pressed = read_debounced_button()
load_level = classify_load(load)
# Step 2: Generate input events
process_inputs(
load,
load_level,
button_pressed
)
# Step 3: Handle priority events first
cycle_protection_timestamp = None
process_priority_events()
# Step 4: Update system state
previous_state = current_state
update_state(button_pressed, load)
# Step 5: Record state transitions
if current_state != previous_state:
print("\nSTATE TRANSITION:")
print(previous_state, "->", current_state)
if current_state == PRIORITY_PROTECTION:
if cycle_protection_timestamp is not None:
response_time = time.ticks_diff(
time.ticks_ms(),
cycle_protection_timestamp
)
if response_time > max_protection_response_ms:
max_protection_response_ms = response_time
print("Protection Response:",
response_time, "ms")
if current_state == NORMAL:
enqueue_event(
create_event("RECOVERY_COMPLETED")
)
# Step 6: Update physical outputs
update_outputs(current_state, load_level)
# Step 7: Process at most one normal event
process_normal_event()
# Step 8: Periodic monitoring
now = time.ticks_ms()
if time.ticks_diff(
now, last_monitor_time
) >= MONITOR_INTERVAL_MS:
display_monitoring(
load,
adc_value,
load_level,
current_state
)
last_monitor_time = now
# Step 9: Measure execution time
cycle_end = time.ticks_ms()
execution_time = time.ticks_diff(
cycle_end, cycle_start
)
if execution_time > max_cycle_execution_ms:
max_cycle_execution_ms = execution_time
if execution_time > LOOP_INTERVAL_MS:
scheduler_overruns += 1
# ==========================================
# 12. Main Program
# ==========================================
print("================================")
print("Thermal Monitoring Controller")
print("Improved Event-Driven Architecture")
print("================================")
print("Initial State:", current_state)
print("Scheduler Interval:", LOOP_INTERVAL_MS, "ms")
print("Normal Queue Capacity: 8")
print("Priority Queue Capacity: 4")
print("Debounce Time:", DEBOUNCE_MS, "ms")
print("Recovery Duration:", RECOVERY_DURATION_MS, "ms")
next_cycle = time.ticks_add(
time.ticks_ms(),
LOOP_INTERVAL_MS
)
while True:
now = time.ticks_ms()
if time.ticks_diff(now, next_cycle) >= 0:
scheduler_cycle()
next_cycle = time.ticks_add(
next_cycle,
LOOP_INTERVAL_MS
)
# Avoid repeated catch-up cycles
# if one scheduler cycle takes too long.
now = time.ticks_ms()
if time.ticks_diff(now, next_cycle) >= 0:
scheduler_overruns += 1
next_cycle = time.ticks_add(
now,
LOOP_INTERVAL_MS
)
else:
# Yield briefly instead of blocking for 50 ms.
time.sleep_ms(1)