← Back to the chapter · Next detail →
Technical detail · Context-Aware Energy Management
Trace a cache-infer-sense decision
The example returns both a context value and its evidence, so the caller can apply and review the policy. It checks the requested maximum age before trying a rule, and records a direct reading in the cache when both shortcuts fail.
def choose_energy_policy(request, cache, rules, sensors, state):
cached = cache.get(request.attribute)
if cached and cached.age_s <= request.max_age_s:
return PolicyDecision("use_cache", cached.value, evidence=cached)
rule = rules.best_rule_for(request.attribute, state.context)
if rule and rule.confidence >= request.min_confidence:
inferred = rule.apply(state.context)
return PolicyDecision("infer_context", inferred, evidence=rule)
reading = sensors.read(request.attribute)
cache.store(request.attribute, reading.value, ttl_s=request.max_age_s)
return PolicyDecision("direct_sense", reading.value, evidence=reading)
These thresholds are not universal. A temperature trend display can tolerate looser freshness than a lock, medical alarm, or industrial safety interlock. The request’s limits must reflect the decision being made.