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)
# ============================================================
# 2. SYSTEM CONFIGURATION
# ============================================================
LOOP_INTERVAL_MS = 50
EMERGENCY_POLL_INTERVAL_MS = 1
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. SYSTEM STATES
# ============================================================
NORMAL = "NORMAL"
PRIORITY_PROTECTION = "PRIORITY_PROTECTION"
RECOVERY = "RECOVERY"
current_state = NORMAL
recovery_start = 0
# ============================================================
# 4. BUTTON DEBOUNCE VARIABLES
# ============================================================
raw_button_state = emergency_button.value()
stable_button_state = raw_button_state
last_change_time = time.ticks_ms()
last_raw_press_timestamp = time.ticks_ms()
# ============================================================
# 5. SYSTEM VARIABLES
# ============================================================
latest_load = 0.0
latest_adc_value = 0
latest_load_level = "LOW"
previous_load_level = None
previous_profile = mode_switch.value()
last_monitor_time = time.ticks_ms()
scheduler_overruns = 0
max_protection_response_ms = 0
max_queue_wait_ms = 0
total_scheduler_cycles = 0
# ============================================================
# 6. LOAD MONITORING
# ============================================================
def read_load():
adc_value = pot.read_u16()
load_percentage = (
adc_value / 65535
) * 100
return load_percentage, adc_value
def classify_load(load):
if load <= 30:
return "LOW"
elif load <= 60:
return "MEDIUM"
elif load <= 80:
return "HIGH"
else:
return "CRITICAL"
# ============================================================
# 7. BUTTON DEBOUNCE
# ============================================================
def read_debounced_button():
global raw_button_state
global stable_button_state
global last_change_time
global last_raw_press_timestamp
current_reading = emergency_button.value()
now = time.ticks_ms()
# Detect a raw button state change
if current_reading != raw_button_state:
raw_button_state = current_reading
last_change_time = now
if current_reading == 0:
last_raw_press_timestamp = now
# Confirm the input after the debounce period
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 True
return False
# ============================================================
# 8. OUTPUT CONTROL
# ============================================================
def set_pwm_percent(pwm, percentage):
duty = int(
percentage * 65535 / 100
)
pwm.duty_u16(duty)
def update_outputs(state, load_level):
if state == NORMAL:
green_percentage = LOAD_LEVELS[load_level]
set_pwm_percent(
green_pwm,
green_percentage
)
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:
green_percentage = LOAD_LEVELS[load_level]
set_pwm_percent(
green_pwm,
green_percentage
)
red_led.value(0)
buzzer_pwm.duty_u16(0)
# ============================================================
# 9. STATE MACHINE
# ============================================================
def update_state(button_pressed, load):
global current_state
global recovery_start
previous_state = current_state
now = time.ticks_ms()
# NORMAL -> PRIORITY_PROTECTION
if current_state == NORMAL:
if (
button_pressed
or load > CRITICAL_THRESHOLD
):
current_state = PRIORITY_PROTECTION
# PRIORITY_PROTECTION -> RECOVERY
elif current_state == PRIORITY_PROTECTION:
if (
not button_pressed
and load <= CRITICAL_THRESHOLD
):
current_state = RECOVERY
recovery_start = now
# RECOVERY -> PRIORITY_PROTECTION
elif current_state == RECOVERY:
if (
button_pressed
or load > CRITICAL_THRESHOLD
):
current_state = PRIORITY_PROTECTION
# RECOVERY -> NORMAL
elif (
time.ticks_diff(
now,
recovery_start
) >= RECOVERY_DURATION_MS
):
current_state = NORMAL
return previous_state, current_state
# ============================================================
# 10. PRIORITY EVENT HANDLING
# ============================================================
def handle_priority_events():
global current_state
global max_protection_response_ms
while get_priority_queue_size() > 0:
event = dequeue_priority_event()
if event is None:
break
event_type = event["type"]
previous_state = current_state
button_pressed = (
stable_button_state == 0
)
# Emergency button pressed
if event_type == "EMERGENCY_PRESSED":
update_state(
True,
latest_load
)
# Emergency button released
elif event_type == "EMERGENCY_RELEASED":
update_state(
False,
latest_load
)
# Critical load detected
elif event_type == "CRITICAL_LOAD_DETECTED":
update_state(
button_pressed,
latest_load
)
# Measure protection response
if (
previous_state != PRIORITY_PROTECTION
and current_state == PRIORITY_PROTECTION
):
response_time = time.ticks_diff(
time.ticks_ms(),
event["timestamp"]
)
if response_time > max_protection_response_ms:
max_protection_response_ms = response_time
print(
"STATE TRANSITION:",
previous_state,
"->",
current_state
)
print(
"Protection Response:",
response_time,
"ms"
)
elif current_state != previous_state:
print(
"STATE TRANSITION:",
previous_state,
"->",
current_state
)
# ============================================================
# 11. FAST EMERGENCY INPUT POLLING
# ============================================================
def fast_emergency_poll():
button_changed = read_debounced_button()
if not button_changed:
return
# Generate an emergency event
if stable_button_state == 0:
event = create_priority_event(
"EMERGENCY_PRESSED"
)
event["timestamp"] = last_raw_press_timestamp
else:
event = create_priority_event(
"EMERGENCY_RELEASED"
)
enqueue_priority_event(event)
# Process the priority event immediately
handle_priority_events()
# Update hardware outputs immediately
update_outputs(
current_state,
latest_load_level
)
# ============================================================
# 12. INPUT EVENT GENERATION
# ============================================================
def process_inputs(load, load_level, profile):
global previous_load_level
global previous_profile
# Generate normal load-level event
if load_level != previous_load_level:
event = create_event(
"LOAD_LEVEL_CHANGED",
load_level
)
enqueue_event(event)
previous_load_level = load_level
# Generate profile-change event
if profile != previous_profile:
event = create_event(
"PROFILE_CHANGED",
profile
)
enqueue_event(event)
previous_profile = profile
# ============================================================
# 13. NORMAL EVENT PROCESSING
# ============================================================
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"] == 1:
print(
"Normal Event: Enhanced Profile"
)
else:
print(
"Normal Event: Standard Profile"
)
elif event_type == "RECOVERY_COMPLETED":
print(
"Normal Event: Recovery Completed"
)
elif event_type == "SYSTEM_DIAGNOSTIC":
print(
"Normal Event: System Diagnostic"
)
record_processed_event()
# ============================================================
# 14. MONITORING DISPLAY
# ============================================================
def display_monitoring(load, adc_value, load_level):
profile = mode_switch.value()
if profile == 1:
print(
"Enhanced | Load:",
round(load, 1),
"% | ADC:",
adc_value,
"| Level:",
load_level,
"| State:",
current_state
)
print(
"Normal Queue:",
get_event_statistics()
)
print(
"Priority Queue:",
get_priority_statistics()
)
else:
print(
"Standard | Load:",
round(load, 1),
"%",
"| Level:",
load_level,
"| State:",
current_state
)
# ============================================================
# 15. NORMAL SCHEDULER CYCLE
# ============================================================
def scheduler_cycle():
global latest_load
global latest_adc_value
global latest_load_level
global last_monitor_time
global scheduler_overruns
global total_scheduler_cycles
cycle_start = time.ticks_ms()
total_scheduler_cycles += 1
# Sample the potentiometer
load, adc_value = read_load()
latest_load = load
latest_adc_value = adc_value
load_level = classify_load(load)
latest_load_level = load_level
profile = mode_switch.value()
# Generate normal events
process_inputs(
load,
load_level,
profile
)
# Detect critical load
if load > CRITICAL_THRESHOLD:
if current_state != PRIORITY_PROTECTION:
event = create_priority_event(
"CRITICAL_LOAD_DETECTED"
)
enqueue_priority_event(event)
handle_priority_events()
# Ensure that the state machine also checks
# the latest sampled load and stable button state.
previous_state, new_state = update_state(
stable_button_state == 0,
latest_load
)
if previous_state != new_state:
print(
"STATE TRANSITION:",
previous_state,
"->",
new_state
)
if new_state == NORMAL:
event = create_event(
"RECOVERY_COMPLETED"
)
enqueue_event(event)
# Update outputs after normal state processing
update_outputs(
current_state,
latest_load_level
)
# Process no more than one normal event per cycle
process_normal_event()
# Periodic monitoring
now = time.ticks_ms()
if time.ticks_diff(
now,
last_monitor_time
) >= MONITOR_INTERVAL_MS:
display_monitoring(
latest_load,
latest_adc_value,
latest_load_level
)
last_monitor_time = now
# Check scheduler execution time
execution_time = time.ticks_diff(
time.ticks_ms(),
cycle_start
)
if execution_time > LOOP_INTERVAL_MS:
scheduler_overruns += 1
# ============================================================
# 16. SYSTEM STARTUP
# ============================================================
print()
print("========================================")
print("Thermal Monitoring Controller")
print("Improved Event-Driven Architecture")
print("Revision 2")
print("========================================")
print("Initial State:", current_state)
print(
"Normal Scheduler Interval:",
LOOP_INTERVAL_MS,
"ms"
)
print(
"Emergency Polling Yield:",
EMERGENCY_POLL_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"
)
print("========================================")
# Initial load sample
latest_load, latest_adc_value = read_load()
latest_load_level = classify_load(
latest_load
)
# Start scheduler
next_cycle = time.ticks_add(
time.ticks_ms(),
LOOP_INTERVAL_MS
)
# ============================================================
# 17. MAIN EXECUTION LOOP
# ============================================================
while True:
# Fast emergency input checking
fast_emergency_poll()
now = time.ticks_ms()
# Run normal tasks every 50 ms
if time.ticks_diff(
now,
next_cycle
) >= 0:
scheduler_cycle()
next_cycle = time.ticks_add(
next_cycle,
LOOP_INTERVAL_MS
)
now = time.ticks_ms()
# Avoid accumulating excessive scheduler delay
if time.ticks_diff(
now,
next_cycle
) >= 0:
scheduler_overruns += 1
next_cycle = time.ticks_add(
now,
LOOP_INTERVAL_MS
)
# Short cooperative yield
time.sleep_ms(
EMERGENCY_POLL_INTERVAL_MS
)