Skip to content
Academia.
ELEmbedded LinuxT550077101 · Fall 2026
CourseFall 2026

Friday · 12:00–16:00 · Odense U174

Home Assistant, Edge AI, Local LLMs, and Intelligent Systems

Lecture 09: This module introduces Home Assistant as an integration and supervision layer, then develops a practical framework for automation, Edge AI, model evaluation, local LLM deployment, and intelligent-system safety. Students learn how to design explicit automation state machines, integrate MQTT and entity/state models, evaluate model outputs using appropriate metrics, avoid data leakage, manage dataset and model lifecycles, build practical Edge-AI pipelines, select local LLM platforms, and enforce authority, privacy, security, and graceful-degradation boundaries.

Learning objectives

✓By the end of this module, students should be able to:
✓• distinguish monitoring, automation, control, and AI functions;
✓• model devices in Home Assistant using entities, states, attributes, devices, areas, and integrations;
✓• design trigger–condition–action automations that are bounded, observable, and restart-safe;
✓• integrate MQTT devices using explicit topics, availability, discovery, command/acknowledgement, and access controls;
✓• explain edge-AI model selection, preprocessing, inference, evaluation, and deployment constraints;
✓• compute and interpret classification and regression metrics such as precision, recall, F1, MAE, and RMSE;
✓• recognize dataset leakage, drift, out-of-distribution inputs, and model-lifecycle risks;
✓• construct practical inference pipelines for sensors, images, and other embedded inputs;
✓• select suitable local LLM hardware, runtime, and deployment architecture;
✓• identify prompt injection, untrusted-output, tool-use, authorization, privacy, and data-governance risks;
✓• design intelligent systems with explicit authority boundaries, fallback behavior, auditability, and safe actuator control;
✓• apply the module concepts in a practical embedded intelligent-system workflow.
Block 112:00–12:50content

Block 1 • Home Assistant Architecture and Automation

CHAPTER 9

Home Assistant, Edge AI, Local LLMs,
and Intelligent Systems

Learning objectives

After completing this module, students should be able to:

  • distinguish monitoring, automation, control, artificial intelligence, and safety functions;
  • model devices in Home Assistant using entities, states, attributes, devices, areas, and integrations;
  • design trigger–condition–action automations that are bounded, observable, and resistant to feedback loops;
  • integrate MQTT devices using explicit topics, availability, discovery, command acknowledgement, and access control;
  • explain edge AI and select suitable processors, accelerators, models, and deployment formats;
  • measure classification, detection, regression, and anomaly-detection performance beyond a single accuracy value;
  • build a reproducible data and model lifecycle that addresses leakage, drift, uncertainty, and versioning;
  • explain the operation and limitations of local large language models;
  • constrain AI-generated decisions with deterministic validation, least privilege, and safe fallback; and
  • produce engineering evidence suitable for a course portfolio and a technical job interview.
Intelligence does not replace engineering
An intelligent embedded system is not merely a sensor connected to a model. It is a complete decision chain containing acquisition, validation, inference, policy, actuation, supervision, security, and recovery. AI may estimate or recommend; the surrounding engineered system decides what authority that estimate is allowed to have.

9.1  From Monitoring to Intelligent Action

The words monitoring, automation, control, and AI are often mixed together, although they describe different functions.

Function Purpose Example
Monitoring Observe and present state without changing the process Display greenhouse temperature and communication age
Rule automation Execute explicit logic after an event or state change Send an alert if soil moisture remains low for 30 minutes
EMBEDDED LINUX Fall 2026
Function Purpose Example
Feedback control Continuously reduce error between a measured and desired state Modulate ventilation to regulate air temperature
Optimization Select actions that improve an objective under constraints Schedule irrigation while limiting water and electricity use
Machine learning Estimate a mapping learned from data Classify whether a leaf image shows disease symptoms
Generative AI Produce new text, code, images, or structured proposals from context Summarize maintenance records and propose diagnostic steps
Safety function Detect or prevent unacceptable physical risk Remove motor power when a guard is opened

A dashboard is not a controller, an automation rule is not necessarily a safety function, and a machine-learning score is not a verified physical fact. The architecture must make these boundaries explicit.

9.2  Home Assistant Architecture

Home Assistant is an open-source integration and automation platform. It can collect device states, expose controls, execute automations, maintain history, and present dashboards. Although it was developed for home automation, the same concepts are useful for laboratories, greenhouses, mobile-robot support systems, and experimental monitoring. It should not be confused with a programmable logic controller, a hard real-time controller, or a certified safety system.

The main Home Assistant concepts are:

Integration: Software that connects Home Assistant to a protocol, product, or service, such as MQTT, Modbus, a weather service, or a smart plug.

Device: A physical or logical product containing one or more entities, such as an ESP32 environmental node.

Entity: One observable or controllable item. Examples are sensor.greenhouse_temperature, binary_sensor.door, and switch.irrigation_pump.

State: The primary current value of an entity. A temperature entity may have state 21.8; a switch may be on or off.

Attribute: Additional metadata associated with an entity, such as unit, battery level, or device class. Attributes should not be used as an uncontrolled database.

Area: A logical or physical grouping such as Greenhouse 1, Barn East, or Robot Laboratory.

Event: A time-stamped occurrence on the internal event bus.

Service or action: An operation that can be requested, such as turning on a switch or sending a notification.

Automation: Logic consisting primarily of triggers, conditions, and actions.

Script: A reusable sequence of actions that may receive parameters.

Scene: A named collection of desired entity states.

Dashboard: A user interface for observing and commanding the system.

EMBEDDED LINUXFall 2026

ChatGPT Image Sep 25, 2026, 08_34_11 PM

Figure 9.1.  Home Assistant is an integration and supervision layer. Time-critical and safety-critical control remains local to an appropriate controller.

9.3  Automations as Explicit State Machines

An automation normally contains:

  1. a trigger, which starts evaluation;
  2. zero or more conditions, which must be true before execution; and
  3. one or more actions, which produce effects.

The important engineering questions are not only “does the rule work?” but also:

  • What happens when the measurement is missing, stale, unavailable, or invalid?
  • Can repeated events create repeated commands?
  • Can the action itself retrigger the automation?
  • What happens if two runs overlap?
  • Is there a minimum on-time, minimum off-time, cooldown, timeout, or rate limit?
  • How is manual override represented, and when does it expire?
  • How will an operator know that the automation failed?

Home Assistant automation modes define what happens when a new trigger arrives while an earlier run is active. single rejects the new run, restart replaces the existing run if the conditions are met, queued preserves the order of admitted runs, and parallel allows concurrent runs. Conditions for admitting a queued run are checked when it is triggered. The correct mode follows the physical process. Concurrent irrigation commands, for example, may be unsafe or wasteful.[68]

EMBEDDED LINUXFall 2026
Listing 9.1.  Illustrative Home Assistant ventilation sequence for a low-risk demonstrator
1alias: Greenhouse high-temperature ventilation
2mode: single
3triggers:
4 - trigger: numeric_state
5 entity_id: sensor.greenhouse_air_temperature
6 above: 30
7 for: "00:05:00"
8conditions:
9 - condition: state
10 entity_id: input_boolean.automatic_climate_control
11 state: "on"
12 - condition: state
13 entity_id: binary_sensor.ventilation_fault
14 state: "off"
15actions:
16 - action: switch.turn_on
17 target:
18 entity_id: switch.greenhouse_fan
19 - wait_for_trigger:
20 - trigger: numeric_state
21 entity_id: sensor.greenhouse_air_temperature
22 below: 27
23 for: "00:03:00"
24 timeout: "00:30:00"
25 continue_on_timeout: true
26 - action: switch.turn_off
27 target:
28 entity_id: switch.greenhouse_fan
29 - if:
30 - condition: template
31 value_template: "{{ wait.completed == false }}"
32 then:
33 - action: notify.operator
34 data:
35 message: "Ventilation stopped after maximum permitted run time."

This example illustrates persistence before activation, separate on/off thresholds, a timeout, an enable condition, an initial fault check, and notification. Replace the example entity IDs and notify.operator with configured entities and an available notification action. The temperature entity must use degrees Celsius because these numeric thresholds compare its state value.

The conditions are checked when the run starts; changing the enable flag or fault entity during the wait does not itself stop the fan. The for timers do not survive automation reload or Home Assistant restart, and cancellation can prevent the final off action. A numeric-state trigger also requires a threshold crossing, so persistent high temperature after the timeout does not automatically start another cycle. These are deliberate limitations of this introductory sequence, not guarantees of continuous regulation. For deployment, add explicit state and freshness supervision, startup reconciliation, and controller-enforced maximum runtime; test each transition.[68]

A motor overload, guard circuit, or emergency stop must be enforced independently where the risk assessment requires it. In a real greenhouse, stopping ventilation may itself worsen overheating, so the fallback must follow the physical hazard analysis rather than assuming that every output should be off.

9.4  Avoiding Automation Failure Patterns

EMBEDDED LINUXFall 2026
Failure pattern Consequence Better design
No hysteresisOutput chatters around a thresholdSeparate on/off thresholds and minimum dwell times
No stale-data checkOld data drives a current decisionCarry observation time and reject excessive age
Action retriggers itselfFeedback loop or command stormSeparate requested and measured state; add guards
Unlimited parallel runsRace conditions and repeated physical actionsSelect a deliberate automation mode
No acknowledgementDashboard claims an action that never occurredReturn commanded, accepted, and measured state separately
Network-only stopActuator remains active after connectivity lossEnforce a local command lease or watchdog
Silent failureOperator assumes the system is healthyPublish availability, diagnostics, and actionable alerts
Hard-coded credentialsSecret exposure and difficult rotationUse secret storage and narrow broker permissions

9.5  MQTT Integration and Discovery

MQTT is a common bridge between embedded nodes and Home Assistant. The broker routes messages but does not by itself know whether a payload is physically credible. A robust device design separates:

  • state topics, which report measured or confirmed state;
  • command topics, which request an action;
  • acknowledgement or result topics, which report acceptance or rejection;
  • availability topics, which report whether the node is operational;
  • configuration or discovery topics, which describe entities; and
  • diagnostic topics, which expose firmware version, reset reason, message age, and faults.
Listing 9.2.  Illustrative MQTT topics and payloads
1eml/v1/greenhouse-01/environment/state
2{"schema":1,"sequence":931,"observed_at":"2026-10-16T10:15:00Z",
3 "temperature_C":28.4,"relative_humidity_pct":64.2,"quality":"valid"}
4 
5eml/v1/greenhouse-01/fan/command
6{"schema":1,"command_id":"c-817","requested_state":"on",
7 "expires_at":"2026-10-16T10:15:10Z"}
8 
9eml/v1/greenhouse-01/fan/result
10{"schema":1,"command_id":"c-817","accepted":true,
11 "measured_state":"on","fault":null}
12 
13eml/v1/greenhouse-01/availability
14online

MQTT discovery publishes configuration that allows Home Assistant to create entities automatically. It is convenient for fleets, but configuration topics effectively influence the user interface and command paths. Restrict which clients may publish discovery messages. Use unique identifiers that remain stable across restarts and do not place credentials or personal information in topic names.

EMBEDDED LINUXFall 2026

Retained state is useful for a new subscriber, but it can be mistaken for a fresh observation. Include an observation timestamp and display data age. A retained command is usually dangerous because a restarted actuator might execute an old request. Commands should normally expire and carry unique identifiers.

Engineering caution
The Home Assistant state of an entity may represent the latest received message, not independently verified physical reality. For consequential actions, distinguish requested state, controller-accepted state, and measured state.

9.6  What Edge AI Means

Artificial intelligence is a broad term for systems performing tasks associated with perception, prediction, reasoning, or decision support. Machine learning learns behavior from data rather than expressing every rule explicitly. Inference applies a trained model to new input. Edge AI executes inference near the data source, such as on a sensor node, mobile robot, gateway, industrial PC, Raspberry Pi, or NVIDIA Jetson.

Edge processing can provide:

  • lower and more predictable communication latency;
  • continued operation during cloud or Internet outages;
  • reduced upstream bandwidth by transmitting events or features instead of raw data;
  • better privacy when images or audio remain on site; and
  • local filtering before data reaches a central service.

The costs include limited memory, compute, energy, thermal capacity, storage, and maintainability. Edge deployment also creates many copies of models and dependencies that must be inventoried, updated, monitored, and rolled back.

9.6.1  Edge and cloud are placement choices

An application need not be entirely local or entirely cloud-based. A useful hybrid architecture may execute time-sensitive detection locally, store selected evidence in a private server, and perform expensive model training centrally. Place each function according to deadlines, privacy, bandwidth, energy, availability, lifecycle, and safety requirements.

Block 213:00–13:50content

Block 2 • Edge AI, Inference, and Model Evaluation

EMBEDDED LINUX Fall 2026

9.7  Typical Edge-AI Hardware

Platform class Strength Typical task Important limitation
Microcontroller Very low power and fast startup TinyML classification, vibration anomaly score, keyword detection Very limited RAM, model size, and operator support
Raspberry Pi CPU Accessible Linux platform with rich ecosystem Modest vision, audio, tabular inference, gateway analytics CPU latency and thermal throttling under sustained load
USB/NPU accelerator Efficient supported neural-network operations Detection or classification with a compatible compiled model Restricted operators, conversion effort, device-specific toolchain
NVIDIA Jetson GPU acceleration and camera/robotics ecosystem Multi-camera perception, detection, segmentation, tracking Power, heat, cost, software-version compatibility
Industrial PC or edge server High performance, storage, and serviceability Multi-sensor fusion, several models, local LLM service Greater power and physical footprint
Cloud service Elastic compute and centralized management Training, fleet analytics, large-model inference Connectivity, recurring cost, privacy, and variable latency

Peak operations per second are not application performance. Measure the complete pipeline on the target hardware: acquisition, resizing, preprocessing, inference, postprocessing, communication, and actuation. Thermal throttling can make a five-minute benchmark misleading for a system that must operate all day.

9.8  A Practical Inference Pipeline

A vision system commonly performs:

  1. image acquisition and timestamping;
  2. quality checks for exposure, blur, obstruction, and missing frames;
  3. resizing, color conversion, normalization, or cropping;
  4. model inference;
  5. postprocessing such as thresholding and non-maximum suppression;
  6. tracking or temporal filtering;
  7. decision policy; and
  8. logging, visualization, or bounded actuation.

ChatGPT Image Sep 25, 2026, 10_11_36 PM
Figure 9.2.  A camera-to-action pipeline separates validation, preprocessing, inference, postprocessing, policy, local control, and physical action. The model produces intermediate results rather than direct actuator authority. Each stage adds latency, and can fail; the listed safeguards are design responsibilities, not evidence of safety certification.
EMBEDDED LINUX Fall 2026

For a mobile agricultural robot, a detector might locate crop rows, weeds, people, or obstacles. A model output is not yet a steering command. Geometry, temporal consistency, confidence, vehicle state, speed limits, and an independently enforced safe stop must be applied before motion.

9.9  Understanding Model Tasks

Classification: Assign a label to an input, such as healthy or diseased leaf.
Object detection: Estimate object classes and bounding boxes, such as people and vehicles in an image.
Segmentation: Assign a class to pixels, useful for crop-row, traversable-area, or weed mapping.
Regression: Estimate a continuous value, such as biomass or remaining battery life.
Anomaly detection: Estimate whether a sample differs from learned normal behavior.
Tracking: Associate detections across time and estimate motion.
Forecasting: Predict future values from a time series.

The model type should match the engineering question. A classifier applied to an entire field image cannot localize the weed that a robot must remove. An anomaly score may indicate unusual vibration without explaining the mechanical cause.

9.10  Metrics That Describe Reality

For binary classification, let TP, TN, FP, and FN denote true positives, true negatives, false positives, and false negatives:

accuracy = TP + TN TP + TN + FP + FN precision = TP TP + FP
recall = TP TP + FN F1 = 2 precision recall precision + recall

These ratios require nonzero denominators. If a class has no actual or predicted positives, report the affected metric as undefined or state the evaluation library’s explicit convention. Accuracy is misleading when classes are imbalanced. If only one image in 100 contains a person, a model that always predicts “no person” obtains 99% accuracy and is operationally useless. Precision answers “when the model reports positive, how often is it right?” Recall answers “of the actual positives, how many did it find?”

  Predicted positive Predicted negative
Actually positive True positive False negative
Actually negative False positive True negative

Threshold selection is a cost decision. A false plant-treatment command wastes chemical or energy; a missed human obstacle can be catastrophic. Report performance over relevant thresholds and define the operating point from consequences rather than convenience.

For regression, useful measures include mean absolute error

MAE = 1 n Σ i=1 n |yi − ŷi|

EMBEDDED LINUX Fall 2026

and root mean square error

RMSE = √ 1 n Σ i=1 n (yi − ŷi)2

These aggregate errors must be complemented by residual plots and performance across seasons, ranges, locations, devices, and operating conditions.

For object detection and segmentation, intersection over union, average precision, per-class recall, small-object performance, and inference latency are relevant. For an embedded system also report:

  • median and high-percentile latency, not only the average;
  • throughput in frames or samples per second;
  • missed deadlines and dropped frames;
  • peak RAM and accelerator memory;
  • energy per inference or average power;
  • sustained temperature and clock behavior; and
  • end-to-end decision latency.

9.11  Data Splitting and Leakage

Training data fits the model, validation data supports choices, and test data estimates final generalization. The test set must not influence tuning. Data leakage occurs when information unavailable during real deployment enters model development or evaluation.

Randomly splitting individual video frames is often invalid because adjacent frames are nearly identical. Agricultural images from the same plant, plot, flight, day, or camera may also be strongly correlated. Split by an independent unit such as field, farm, animal, robot run, date, or season according to the intended claim.

Define the deployment population first
Before splitting data, state where, when, and on what equipment the model is expected to work. A model tested on random samples from one greenhouse has not demonstrated transfer to another greenhouse, season, camera, or crop.

9.12  Dataset and Model Lifecycle

A reproducible model release should record:

  • dataset identity, collection conditions, consent or lawful basis, and provenance;
  • inclusion and exclusion criteria;
  • annotation instructions and reviewer agreement;
  • train/validation/test split method;
  • preprocessing and augmentation;
  • architecture, initialization, optimizer, and training settings;
  • software dependencies and random seeds where meaningful;
  • output semantics and decision threshold;
  • target hardware and measured resource use;
  • known limitations and excluded operating conditions; and
  • model, configuration, and firmware versions.
EMBEDDED LINUX Fall 2026

Use a model registry or equivalent inventory. Rollout should support staged deployment, monitoring, and rollback. A hash can confirm that the loaded artifact matches the approved artifact. Signing can authenticate its source.

9.13  Drift and Out-of-Distribution Inputs

Data drift is a change in the input distribution. Concept drift is a change in the relationship between inputs and desired outputs. Causes include seasons, lighting, camera replacement, dirt, sensor aging, new crop varieties, different operators, and changes in process behavior.

A model can be confidently wrong on input unlike its training data. Softmax confidence is not a guarantee of correctness. Practical defenses include input-quality checks, operating-envelope monitoring, conservative thresholds, ensembles or uncertainty estimates where justified, periodic labeled audits, and fallback when the input is outside the validated domain.

9.14  Compression and Deployment Formats

Quantization represents weights and sometimes activations with reduced numerical precision. Pruning removes selected weights or structures. Knowledge distillation trains a smaller student model to reproduce useful behavior of a larger teacher. These techniques may reduce memory, latency, or energy, but can affect classes and conditions unequally.

Common deployment representations include TensorFlow Lite, ONNX, OpenVINO formats, and vendor-specific optimized engines such as TensorRT. Conversion can change supported operators, numerical behavior, dynamic shapes, and preprocessing expectations. Validate the converted model on the same locked test set and on the actual target.

Listing 9.3.  Measuring an inference function rather than guessing its speed
1from math import ceil
2from statistics import median
3from time import perf_counter
4
5def benchmark(predict, samples, warmup=20, synchronize=None):
6 if len(samples) == 0:
7 raise ValueError("at least one sample is required")
8  if type(warmup) is not int or warmup < 0:
9 raise ValueError("warmup must be a nonnegative integer")
10 # Supply the runtime’s device barrier for asynchronous execution.
11 sync = synchronize if synchronize is not None else lambda: None
12 for sample in samples[:warmup]:
13 predict(sample)
14 sync()  
15
16  latency_ms = []
17 for sample in samples:
18 sync()
19 start = perf_counter()
20 predict(sample)
21 sync()
22 latency_ms.append((perf_counter() - start) * 1000.0)
23
24  # Empirical nearest-rank percentile; no tail extrapolation.
25 p95 = sorted(latency_ms)[ceil(0.95 * len(latency_ms)) - 1]
26 return {
27 "count": len(latency_ms),
28 "median_ms": median(latency_ms),
29 "p95_ms": p95,
EMBEDDED LINUX Fall 2026
29 "p95_ms": p95,
30 "max_ms": max(latency_ms),
31 }

This benchmark expects an indexable collection and a callable predict. It excludes acquisition and postprocessing unless they are deliberately placed inside predict. For an asynchronous accelerator, supply a synchronization callback that waits for the relevant device work to finish; otherwise the timer may measure only submission time. For example, PyTorch provides torch.cuda.synchronize for CUDA work. The nearest-rank p95 is coarse for a small sample; report the count and run long enough to observe thermal effects. Record the target configuration and measure throughput separately when pipelining matters.

9.15  Useful Embedded-AI Examples

Application Possible model output Required engineering beyond the model
Precision weeding Crop/weed mask or plant coordinates Camera calibration, timing, tool geometry, exclusion zones, missed-plant policy
Livestock monitoring Animal detection, posture, or activity Identity uncertainty, occlusion, welfare protocol, privacy, human confirmation
Predictive maintenance Bearing anomaly score Operating regime, sensor mounting, alarm persistence, diagnostic confirmation
Greenhouse disease support Symptom class and confidence Representative lighting/cultivars, expert confirmation, treatment authorization
Mobile-robot safety perception Person or obstacle detection Independent protective sensing, stopping distance, fault detection, certified safety chain
Quality sorting Defect class or grade Traceable ground truth, reject mechanism timing, manual inspection sampling
Energy forecasting Future load or generation Weather quality, uncertainty bounds, constraint-aware scheduler, safe fallback

The right baseline may be a threshold, linear regression, physical model, or conventional image-processing method. AI is justified only when it produces a measurable benefit under representative conditions.







Block 314:00–14:50content

Block 3 • Local LLMs, Deployment, and Intelligent-System Risks

EMBEDDED LINUX Fall 2026

9.16  Local Large Language Models

A large language model predicts token sequences from context learned during training. It does not retrieve truth from a guaranteed database and does not inherently understand the physical system. A local LLM executes on equipment controlled by the organization or user rather than sending every request to an external inference service.

Potential benefits include local operation, reduced external disclosure, predictable local integration, and the ability to use private documents. Limitations include substantial memory and compute requirements, slower inference on small hardware, model maintenance, licensing considerations, and continued risk of fabricated or inappropriate output.

Important terms are:

Token: A model input or output unit, often part of a word.

Context window: The maximum working sequence of tokens available to a model invocation.

Temperature: A sampling parameter influencing output variability; it does not measure factual confidence.

Quantized model: A model stored or executed at reduced numerical precision to reduce resource use.

Prompt: Instructions and data supplied to the model.

System instruction: Higher-level behavioral guidance supplied by the application.

Tool calling: The model proposes a structured request to an external function; the application decides whether and how to execute it.

Hallucination: Fluent output unsupported by facts or supplied evidence.

Retrieval-augmented generation: Retrieval of relevant documents followed by generation using the retrieved context.

Embedding: A numerical representation used for similarity search; similarity is not proof of correctness.

9.17  Selecting and Running a Local LLM

Model choice depends on task quality, license, language, context length, memory, latency, energy, and supported runtime. Parameter count alone does not determine usefulness. Quantization can make a model fit on smaller equipment, but quality and speed must be tested on the actual prompts and hardware.

A local runtime can expose an HTTP API to applications. This is convenient but creates a network service that must be authenticated or bound to a trusted interface. Do not assume that “local” automatically means private: prompts may be logged, stored in shell history, included in backups, exposed through dashboards, or sent through external tools.

EMBEDDED LINUX Fall 2026
Listing 9.4.  Treating a local LLM response as an untrusted proposal
1import json
2import math
3 
4ALLOWED_ACTIONS = {"notify_operator", "request_inspection"}
5 
6def unique_object(pairs):
7    result = {}
8    for key, value in pairs:
9        if key in result:
10            raise ValueError("duplicate JSON key")
11        result[key] = value
12    return result
13 
14def validate_proposal(raw_text: str) -> dict:
15    if not isinstance(raw_text, str) or len(raw_text) > 4096:
16        raise ValueError("invalid or oversized response")
17    proposal = json.loads(raw_text, object_pairs_hook=unique_object)
18    if not isinstance(proposal, dict):
19        raise ValueError("expected a JSON object")
20    if set(proposal) != {"action", "reason", "confidence"}:
21        raise ValueError("unexpected output schema")
22    action = proposal["action"]
23    if not isinstance(action, str) or action not in ALLOWED_ACTIONS:
24        raise ValueError("action is not authorized")
25    confidence = proposal["confidence"]
26    if type(confidence) not in (int, float):
27        raise ValueError("confidence must be a JSON number")
28    if not 0.0 <= confidence <= 1.0 or not math.isfinite(confidence):
29        raise ValueError("invalid confidence")
30    reason = proposal["reason"]
31    if not isinstance(reason, str) or not 1 <= len(reason.strip()) <= 500:
32        raise ValueError("reason must contain 1 to 500 characters")
33    return {"action": action, "reason": reason.strip(),
34        "confidence": float(confidence)}
35 
36# Validation does not prove the reason is true. The permitted actions are
37# intentionally advisory and cannot energize a physical actuator.

Requiring JSON improves parsing, not truthfulness. Validate schema, values, authorization, data freshness, and physical constraints after generation. A model’s self-reported confidence is not calibrated probability and must not grant authority. The caller must reject parsing or validation errors, cap the response before buffering it, and separately enforce tool permissions and rate limits.[74]

9.18  Retrieval-Augmented Generation for Technical Notes

Retrieval-augmented generation can support a local maintenance assistant:

  1. ingest approved manuals, wiring diagrams, and procedures;
  2. divide them into traceable chunks;
  3. create a searchable index;
  4. retrieve passages relevant to a question;
  5. ask the model to answer only from those passages; and
  6. display document identity, revision, and citations to the operator.

This reduces but does not eliminate fabrication. Retrieval may select an obsolete manual, omit an exception, or find a procedure for another equipment variant. High-consequence instructions require authoritative document control and human verification.

9.19  Prompt Injection and Tool Safety

Prompt injection occurs when untrusted content attempts to redirect the model or override intended behavior. A webpage, log entry, email, QR code, or retrieved document can contain hostile instructions. The model should never determine its own authority.

For an LLM-enabled embedded or automation system:

  • separate data from instructions where possible;
  • maintain a small allowlist of narrow tools;
  • validate every tool argument independently;
  • require confirmation for consequential operations;
  • run tools with least privilege and bounded time/resources;
  • prevent arbitrary shell, file, database, or network access;
  • log proposed and executed actions with secret redaction; and
  • assume external and retrieved content may be malicious.
EMBEDDED LINUX Fall 2026
ChatGPT Image Sep 26, 2026, 01_28_02 AM(1)
Figure 9.3.
Model recommendations and authorized operator requests pass through deterministic policy and applicable interlocks before local execution. Independent protection can inhibit actuation without relying on the AI path. Manual operation does not bypass applicable interlocks or independent stop functions.
Engineering caution
Never connect free-form LLM output directly to motor motion, pesticide application, heating, access control, or another consequential actuator. The model may suggest an intention; deterministic software and independently enforced physical limits must decide whether any action is permitted.

9.20  Authority Architecture for Intelligent Systems

A useful design divides decisions into authority levels:

Level Permitted behavior Example
Observe Read approved data Summarize greenhouse conditions
Recommend Suggest a non-binding action Recommend inspecting fan 2
Prepare Generate a bounded draft for review Prepare an irrigation schedule within stated limits
Execute
reversible
Perform a narrow low-consequence action Create a maintenance ticket after validation
Execute
physical
Command a physical process Allowed only through deterministic physical authorization, constraints, interlocks, and appropriate assurance
Safety authority Prevent or remove hazard Reserved for an independent, engineered safety function

The strongest design often gives AI less authority than users initially imagine. This is not a weakness; it makes useful automation deployable without allowing one uncertain component to control the whole system.

EMBEDDED LINUX Fall 2026

9.21  Fallback and Graceful Degradation

Define behavior for each of the following:

  • the model service is unavailable;
  • inference exceeds its deadline;
  • input quality is insufficient;
  • model confidence or uncertainty is unacceptable;
  • the input is outside the validated operating domain;
  • the accelerator overheats or runs out of memory;
  • a new model fails after deployment; and
  • the network, broker, dashboard, or database is unavailable.

Possible degraded behaviors include retaining the last safe command only for a bounded lease, returning to a conservative rule-based strategy, reducing speed, suspending automatic action, storing data locally, and requesting human intervention. A fallback must itself be tested. “The operator will notice” is not a dependable mechanism unless the detection, notification, response time, and authority have been designed.
































Block 415:00–15:50content

Block 4 • Authority, Safety, Security, and Practical Integration

EMBEDDED LINUX Fall 2026

9.22  Privacy and Data Governance

Local inference can reduce external data transfer but does not solve privacy automatically. Cameras, audio, location, identifiers, and behavioral records may still be personal or sensitive data. Apply data minimization: collect only what the stated purpose requires, retain it only as long as justified, protect access, and document who can use it.

Separate raw data, annotations, derived features, model outputs, and audit logs. Each may have different retention and access requirements. Before using captured data for a new research or teaching purpose, verify that the original basis and participant information permit it. Anonymization is difficult when video, trajectories, or location patterns can identify individuals indirectly.

9.23  Security of Home Assistant and AI Services

An integration platform concentrates credentials and control. Protect it accordingly:

  • keep Home Assistant, add-ons, operating system, and integrations updated;
  • use strong unique authentication and multifactor authentication where supported;
  • do not expose services directly to the Internet without a justified secure architecture;
  • segment IoT devices from administrative systems;
  • use TLS and narrow MQTT access-control lists;
  • store secrets outside public repositories and rotate them after exposure;
  • disable unused integrations and remove abandoned accounts;
  • back up configuration and test restoration;
  • restrict local model APIs and tool permissions; and
  • monitor authentication failures, unexpected entity creation, and unusual commands.

Availability is part of security. A malicious or faulty client can flood MQTT, exhaust model memory, fill storage with images, or generate repeated automations. Apply quotas, payload limits, timeouts, queue bounds, and resource isolation.

9.24  Practical System Example

Consider a greenhouse monitoring system with BME280 environment sensing, soil-moisture probes, a camera, ventilation fans, and irrigation valves.

  1. An ESP32 validates sensor readings and publishes time-stamped MQTT measurements.
  2. Home Assistant presents current values, data age, device availability, and manual controls.
  3. A deterministic automation alerts on prolonged temperature excess and may request ventilation within maximum-runtime constraints.
  4. A Raspberry Pi or Jetson performs local leaf-image inference and publishes a disease-risk observation with model version and image-quality status.
  5. The AI result creates an inspection request; it does not directly apply treatment.
  6. A local LLM summarizes recent alarms using approved records and cites their timestamps.
  7. A PLC or microcontroller enforces pump interlocks, dry-run protection, maximum valve duration, and emergency behavior.
  8. Operators can override ordinary automation, while physical safety protection remains independent.
EMBEDDED LINUX Fall 2026

This architecture uses each tool where it is strong: microcontrollers for bounded local behavior, Home Assistant for integration and supervision, edge AI for perception, an LLM for human-facing synthesis, and deterministic hardware/software for authority.

9.25  Guided Laboratory

Guided laboratory: measured intelligent automation

Build a small end-to-end system using one physical or simulated sensor, MQTT, Home Assistant, and one intelligent feature.

Part A—integration and automation

  1. Publish a versioned sensor payload containing device identity, sequence, observation time, unit, value, and quality.
  2. Create a Home Assistant entity with availability and a visible stale-data indication.
  3. Build one bounded automation with persistence, hysteresis or cooldown, maximum action duration, and manual enable/disable.
  4. Demonstrate that a retained or stale message cannot initiate an unsafe action.

Part B—intelligent feature

  1. Select a measurable task such as image classification, anomaly detection, or short technical summarization.
  2. Implement a non-AI baseline.
  3. Record dataset or document provenance and divide evaluation data without leakage.
  4. Measure task quality, median and 95th-percentile latency, memory, temperature, and failure behavior on the target.
  5. Publish the result with model identity, input timestamp, output score, and validity status.

Part C—fault injection Test at least six of the following cases: missing input, stale input, boundary value, malformed MQTT payload, broker loss, model-service failure, high inference latency, and system restart. Demonstrate a safe and visible fallback.

Portfolio evidence
Include the system and trust-boundary diagrams, entity/topic dictionary, automation listing, non-AI baseline, dataset or document provenance, model/runtime version, confusion matrix or task-appropriate metrics, target-device latency and resource measurements, fault-injection evidence, privacy analysis, authority table, and proof that model output cannot bypass deterministic limits.

9.26  Self-Assessment and Job-Interview Questions

The following questions assess this course material while preparing students for embedded-systems, IoT, automation, robotics, and edge-AI interviews. Strong answers state assumptions, identify failure modes, and connect software behavior to physical consequences.

  1. What is the difference between a Home Assistant device and an entity?
  2. Explain triggers, conditions, and actions using an agricultural example.
  3. Why does hysteresis matter in physical automation?
  4. What is the difference between requested, accepted, and measured actuator state?
EMBEDDED LINUX Fall 2026
  1. Why can a retained MQTT message be dangerous on a command topic?
  2. Compare monitoring, automation, feedback control, and a safety function.
  3. Define edge AI and give three reasons to use it.
  4. Why is model accuracy alone inadequate?
  5. A dataset contains 1,000 images, of which 20 contain a hazard. A model reports every image as safe. What is its accuracy, and why is this result unacceptable?
  6. Distinguish precision and recall. Which would you prioritize for person detection on a moving robot?
  7. What is data leakage, and why can a random video-frame split often invalid?
  8. Distinguish data drift and concept drift.
  9. Why must a converted or quantized model be tested again?
  10. What measurements belong in an edge-inference benchmark?
  11. What is a local LLM, and what does “local” fail to guarantee?
  12. Why is low temperature in an LLM not a truth guarantee?
  13. What is retrieval-augmented generation, and what can still go wrong?
  14. What is prompt injection?
  15. Why is valid JSON from an LLM not necessarily a valid engineering command?
  16. Design a safe authority boundary for an AI-assisted irrigation system.
  17. What should happen when an edge model misses its deadline?
  18. Why should a rule-based baseline be implemented before claiming an AI benefit?
  19. How would you detect that a Home Assistant sensor is stale rather than merely unchanged?
  20. What evidence would persuade you that an automation survives a broker outage?
  21. When should Home Assistant not be used to control a process?

9.27  Answers and Discussion

  1. A device represents a physical or logical product; an entity represents one observable or controllable function belonging to that product. One weather node may contain temperature, humidity, battery, and availability entities.
  2. A soil-moisture value remaining below a threshold for 30 minutes can be the trigger. Conditions may require automatic mode, adequate tank level, and no pump fault. Actions may request a bounded irrigation cycle and notify the operator. Physical protection remains local.
  3. Noise near one threshold can repeatedly switch an actuator. Different on and off thresholds create a dead band, reducing chatter, wear, and unstable interaction. Persistence and minimum dwell time may also be required.
  4. Requested state is what a client asks for; accepted state means the controller validated and admitted the request; measured state is obtained from feedback about the physical output. They can differ because of rejection, delay, disconnection, or mechanical failure.
  5. A broker can deliver a retained command to a device after reconnection or restart. The command may be old but still syntactically valid. Prefer non-retained commands with identifiers, expiration, authorization, and explicit acknowledgement.
  6. Monitoring observes; automation executes explicit event-driven rules; feedback control continuously acts on process error; a safety function prevents or mitigates unacceptable risk with an assurance level appropriate to that risk. One platform can support several roles, but the roles must not be confused.
  7. Edge AI performs inference near the source. Reasons include low latency, offline operation, bandwidth reduction, privacy, and local filtering. These benefits must be balanced against compute, power, thermal, and maintenance limits.
  8. Accuracy hides class imbalance and different error costs. The engineer must consider confusion matrices, precision, recall, class-specific performance, thresholds, latency, resource use, robustness, and representative field conditions.
EMBEDDED LINUX Fall 2026
  1. The accuracy is 980/1000 = 98%. Recall for the hazard class is zero because all 20 hazards are missed. A high aggregate accuracy therefore conceals complete failure at the purpose of the detector.
  2. Precision measures how often positive predictions are correct; recall measures how many actual positives are detected. Person-safety perception usually demands high recall, but false positives and stopping behavior also require system-level analysis. The detector must not be the only protective mechanism.
  3. Leakage allows information correlated with the answer or test cases into training or tuning. Adjacent video frames are near duplicates, so random frame splitting lets the model see almost the same scenes in both training and test sets. Split by independent runs, locations, subjects, or dates.
  4. Data drift changes the input distribution, such as lighting or camera properties. Concept drift changes the mapping from input to desired output, such as a changed relationship between symptoms and diagnosis. Both can reduce deployed performance.
  5. Conversion may change precision, operators, preprocessing, shapes, or numerical results. Performance and task quality must be remeasured on the locked evaluation set and target hardware.
  6. Report end-to-end median, high-percentile, and maximum latency; throughput; missed deadlines; memory; power or energy; sustained temperature and clocks; model and runtime versions; preprocessing; batch size; and task accuracy on representative inputs.
  7. A local LLM runs on locally controlled infrastructure. It does not guarantee secrecy, factual correctness, legal compliance, absence of logs, or offline behavior if the surrounding application calls external services.
  8. Temperature changes sampling variability. A deterministic or low-variability answer can still repeat the same false claim. Factual confidence requires evidence and verification, not a generation setting.
  9. Retrieval-augmented generation retrieves relevant material and supplies it to the model. Retrieval can miss the right passage, select obsolete or malicious text, confuse equipment variants, or be summarized incorrectly. Display authoritative sources and revisions.
  10. Prompt injection is untrusted content designed to alter model behavior or induce unintended tool use. Retrieved pages, documents, sensor labels, and log messages must be treated as data rather than trusted instructions.
  11. JSON proves only that parsing may succeed. The content can be false, stale, unauthorized, outside physical limits, or malicious. Deterministic validation and authorization remain mandatory.
  12. Let AI estimate need and provide a recommendation. A deterministic policy checks sensor quality, data age, tank state, weather constraints, allowed duration, rate limits, and operator mode. A local controller applies valve and pump interlocks, and independent protection prevents dry running or excessive pressure.
  13. Discard or mark the late result according to its event time, enter a defined degraded mode, expose diagnostics, and use a validated baseline or safe state. Acting on an old inference may be worse than having no inference.
  14. A baseline reveals whether AI adds measurable value over simple logic and provides a fallback. Without it, complexity may be mistaken for improvement.
  15. Carry an observation timestamp or monotonically increasing sequence from the source and calculate age independently. An unchanged valid temperature may be fresh; a repeatedly displayed retained value may be stale.
  16. Demonstrate bounded local buffering or a stated discard policy, visible unavailability, no unsafe retained commands, controlled reconnection with backoff, duplicate handling, time-stamped replay, and recovery measurements after restoring the broker.
EMBEDDED LINUX Fall 2026
  1. Do not use it as the sole controller where hard real-time timing, certified functional safety, deterministic machine sequencing, or independent emergency response is required. It remains useful as a supervisory and integration layer above an appropriate local controller.

9.28  Authoritative References and Verification Links

The platforms and interfaces in this field evolve. Students should verify versions and configuration using primary documentation:

Chapter summary
Home Assistant is a powerful integration and supervision platform, but it is not automatically a real-time or safety controller. Reliable automations require clear state semantics, freshness, hysteresis, time bounds, acknowledgement, observability, and local fallback. Edge AI can reduce latency, bandwidth, and external data transfer, but it must be evaluated with representative data, task-appropriate metrics, end-to-end latency, sustained resource measurements, and explicit operating limits. Local LLMs remain probabilistic and vulnerable to false output and prompt injection. They are most useful as bounded assistants whose proposals pass through deterministic validation and least-privilege tools. In every intelligent physical system, authority, safety, and recovery belong to the engineered architecture rather than to the model.

Summary

This module presents a practical architecture for intelligent embedded systems centered on Home Assistant, Edge AI, and local language models. It covers automation state machines, MQTT integration and discovery, edge inference pipelines, model metrics and evaluation, dataset leakage and drift, model lifecycle management, embedded-AI hardware, local LLM deployment, retrieval-augmented generation, prompt injection, authority boundaries, privacy, data governance, security, fallback behavior, and graceful degradation. The module concludes with a guided laboratory and self-assessment framework for designing safe, observable, and maintainable intelligent systems.

Course outline

What we will learn

From Linux foundations to physical interfaces, networking, security and a complete embedded system.

Linux foundationsKernel, users, processes and file systems
Command lineShells, scripting and automation
Embedded hardwareBoot, storage and device drivers
Physical I/OGPIO, sensors and actuators
Device busesUART, I²C and SPI
NetworkingTCP/IP, SSH and remote management
Distributed systemsMessage passing and cooperating nodes
Engineering practiceGit, testing, logging and deployment
SecurityLeast privilege, updates and secrets

Teaching method

Short introductions are followed by laboratory activities. Work is normally completed in teams of three. Each team develops an embedded Linux system; the examination portfolio is individual.

Project ideas

Applications you could build

Each project should begin with one reliable end-to-end function.

Automatic Raspberry Pi-based GPS trackerSample examination report available in PDF format
Environmental monitoring stationValidated sensing, local storage and dashboard
Energy monitoring systemMeasure, log and visualize equipment power use
Greenhouse automationClimate sensing, actuation and remote supervision
Field-robot telemetryLocation, operating state, measurements and faults
LoRaWAN sensor networkField nodes, TTN integration and private cloud
Intelligent irrigationSensing, decisions, valves and safe failure handling
Multi-node IoT gatewayProtocol translation, buffering and secure forwarding
ROS 2 communication systemDistributed nodes, QoS and service integration
Edge-AI monitoring systemLocal inference, measured performance and safe fallback

A complete project should demonstrate

NeedA clear user and purpose
Physical interfaceA sensor, actuator or device
Linux integrationPrograms, scripts or services
CommunicationA justified data-exchange method
ReliabilityLogging and failure handling
EvidenceTests, results and reflection

Contractor and client roles

Project groups

Each group develops a project for one client group and evaluates the project received from another contractor group.

Contractor

Heros

ProjectProject 01
Delivers to
Client not assigned
Receives from
Contractor not assigned

Fridays · four 50-minute slots · Odense

Fall 2026 lecture plan

The SDU timetable remains authoritative for dates, times and rooms.

Project progression

Project ideas and proposals begin in Module 1 and evolve throughout the course. Module 10 is the formal integration, architecture and verification review; Modules 11–12 complete implementation, demonstration and individual portfolio evidence.

Lecture 09 · participation

Student questions

Questions remain hidden until the student is called. Model answers are revealed separately.

Instructor classroom view

The roster, answers, attendance and participation records are available only to the authorized primary owner after sign-in.

Instructor sign in

Definitions

Essential course vocabulary

Plain-language definitions for the technical terms used throughout the course.

TermDefinitionExample
ActuatorA device that produces a physical action.Motor, valve, relay or fan
BootThe sequence that starts the hardware, kernel, services and applications.Starting an embedded computer
CLIA text interface that accepts commands.Windows Terminal or a Linux terminal
CommandAn instruction interpreted by a shell.pwd, ls or Get-Location
Device driverSoftware through which the operating system communicates with hardware.GPIO or camera driver
DirectoryA named container for files and other directories./home/student/eml
DistributionA complete operating system built around the Linux kernel.Ubuntu or Debian
Embedded systemA computer integrated into a larger product for a defined purpose.Greenhouse controller
File systemThe structure used to name, store and retrieve files.ext4
GPIOA configurable digital input or output pin.Reading a switch
I²CA two-signal serial bus for peripherals.Environmental sensor
KernelThe privileged core managing memory, processors, devices and processes.Linux kernel
MQTTA lightweight publish/subscribe messaging protocol.Sending sensor data
ProcessA running instance of a program.A data logger
PWMRapid switching used to control average power or a signal duty cycle.Motor speed
RootThe privileged Linux user or the top directory, depending on context.Administrative access
ScriptA file containing commands that automate work.A backup script
SensorA device that converts a physical quantity into data.Temperature sensor
ServiceA background program providing an ongoing function.SSH server
ShellA program that interprets commands and starts programs.Bash or PowerShell
SPIA synchronous bus commonly used for fast peripherals.Display or converter
SSHEncrypted remote command-line access.Managing a Raspberry Pi
TCP/IPThe principal protocol family used across computer networks.Device-to-server communication
UARTAn asynchronous serial interface.Debug console
User spaceThe environment where ordinary programs run outside the kernel.Application software
Version controlA system that records and manages file changes.Git

Official examination information · EKA T550077102

Individual portfolio examination

Form

Portfolio

Individual presentation portfolio submitted at semester end.

Grade

7-point scale

No second examiner.

Weighting

No split published

No separate written-exam or coursework percentages are stated.

Re-examination

Same form

Same form as the ordinary examination.

Team project and individual assessment

The team project creates practical evidence, but each student is assessed individually through the presentation portfolio. Classroom participation points support engagement and do not form part of the official grade.

Document from the beginning

  • Your own decisions and identifiable contribution
  • Commands, code, configuration and version history
  • Tests, results, failures and improvements
  • Reflection on trade-offs and learning

People and course systems

Contacts and official links