Device Gateway & MQTT broker pub/sub messaging
Solves A managed, always-on broker devices publish to and subscribe from over MQTT (topics like fridge/kitchen-01/inventory) β scaling to huge fleets without you running a message broker.
An IoT hub is great at getting signals off physical devices and into the cloud reliably and securely. An agent is great at deciding what to do about a signal. Wire them together and a device event can trigger reasoning and real-world action β like a fridge noticing it's low on milk and ordering more.
This is the "sense β decide β act" loop that underlies most useful IoT-plus-AI systems: predictive maintenance, energy optimization, and here, autonomous replenishment. The fridge is a friendly stand-in for any device that should trigger an intelligent response.
The integration works because each side does a job the other shouldn't. Keeping that split clean is the whole design.
Securely connects millions of devices, ingests telemetry over MQTT, tracks each device's state, and routes events to the cloud. It moves signals; it doesn't reason.
Receives an event and decides: gather context via tools, weigh options, act, or ask a human. It reasons; it doesn't talk to devices directly.
Four primitives do almost all the work in this example:
Solves A managed, always-on broker devices publish to and subscribe from over MQTT (topics like fridge/kitchen-01/inventory) β scaling to huge fleets without you running a message broker.
Solves Every device gets its own certificate and a scoped policy, so a fridge can only publish to its own topics. This is what makes device-triggered actions trustworthy.
Solves A JSON document of each device's reported and desired state. The cloud can read the fridge's last state when it's asleep, and set a desired value (e.g. "milk ordered") the device syncs on reconnect.
Solves A SQL-like rule evaluates every incoming message and routes matches to targets (Lambda, EventBridge, DynamoDB, SNSβ¦). This is the bridge from "a message arrived" to "invoke the agent" β with a condition, so only genuinely low stock wakes the brain.
Five stages connect the sensor to a placed order. The same shape works for any "device event β intelligent action" system.
ββββββββββββ MQTT ββββββββββββββββββββ AWS IoT Core ββββββββββββββββββββ
β Fridge βββpublishβββΆ β Device Gateway β Rules Engine (SELECT β¦ WHERE β
β (sensor) β telemetry β level_pct < 10) β Lambda / EventBridge target β
ββββββ²ββββββ βββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββ
β desired: "ordered" β invoke
β (Device Shadow) βΌ
ββββββ΄ββββββββββββββββ ββββββββββββββ Bedrock AgentCore Runtime βββββββββ
β notify_user (SNS) ββββactβββ Strands agent + Memory (budget, past buys) β
ββββββββββββββββββββββ β tools: inventory Β· price Β· budget Β· order β
βββββββββββββββββββββββββ¬βββββββββββββββββββββββββ
βΌ place_order
βββββββββββββββββ
β Grocery API β
βββββββββββββββββ
| # | Stage | What happens |
|---|---|---|
| 1 | Sense | A weight/vision sensor sees the milk shelf drop below threshold; the fridge publishes an MQTT event (and updates its Device Shadow). |
| 2 | Ingest & route | IoT Core authenticates the device, and a Rules Engine rule with WHERE level_pct < 10 forwards only low-stock events to a Lambda that invokes the agent. |
| 3 | Reason | The Strands agent on AgentCore checks on-hand inventory, gets a live price, and confirms the purchase fits the monthly budget. |
| 4 | Act | It places the smallest sensible order via the grocery tool β or requests human approval if over the spend limit β and notifies the owner over SNS. |
| 5 | Close the loop | It writes the purchase to memory and sets the fridge's Device Shadow desired state to "milk: ordered" so the door display updates. |
Follow one carton of milk through the system.
A load cell under the milk shelf reads 5% of a full carton. Rather than decide anything, the fridge just reports a fact to its own topic: { "item": "milk", "level_pct": 5 }. Dumb device, single responsibility.
Most messages are normal levels and are ignored. This one matches the rule's level_pct < 10 condition, so IoT Core hands it to the trigger Lambda β which turns the raw event into a natural-language task and invokes the agent.
The agent calls get_inventory("milk") (none in the pantry), check_price("milk") ($3.49), then within_budget(3.49) (true). Small, in-budget, needed β it proceeds.
place_order("milk", 1) submits to the grocery partner; notify_user(...) pushes "Ordered 1Γ milk ($3.49) β arriving tomorrow." Had it been a $120 case of steaks, the agent would have called request_approval instead and waited.
The agent records the spend in AgentCore Memory (so next week's budget math is right) and sets the Device Shadow desired state to milk: ordered; the fridge's screen shows "milk on the way," and won't re-trigger for the same carton.
Five files, one per stage. Switch tabs; hit Copy to grab any snippet. (APIs evolve fast β treat these as a faithful sketch and confirm names against current docs.)
# fridge_device.py β runs ON the fridge (AWS IoT Device SDK v2).
# Its ONLY job: sense and report. No business logic, no credentials to shops.
import json
from awscrt import mqtt
from awsiot import mqtt_connection_builder
conn = mqtt_connection_builder.mtls_from_path(
endpoint="xxxx-ats.iot.us-east-1.amazonaws.com",
cert_filepath="fridge.cert.pem", # this device's X.509 identity
pri_key_filepath="fridge.private.key",
ca_filepath="AmazonRootCA1.pem",
client_id="fridge-kitchen-01",
)
conn.connect().result()
# A load cell says the milk shelf is nearly empty β just report the fact.
event = {"deviceId": "fridge-kitchen-01", "item": "milk", "level_pct": 5}
conn.publish(
topic="fridge/kitchen-01/inventory",
payload=json.dumps(event),
qos=mqtt.QoS.AT_LEAST_ONCE,
)
-- iot_rule.sql β AWS IoT Core Rules Engine.
-- Evaluated on EVERY message to fridge/+/inventory, but only LOW stock
-- passes the WHERE clause, so the agent is woken only when it matters.
SELECT deviceId, item, level_pct
FROM 'fridge/+/inventory'
WHERE level_pct < 10
-- Rule action: invoke the Lambda `restock_trigger` (or send to an
-- EventBridge bus). Configure via the console, CLI, or CDK, e.g.:
-- aws iot create-topic-rule --rule-name restock_when_low \
-- --topic-rule-payload file://rule.json
-- where rule.json sets "sql" to the query above and "actions" to the Lambda.
# restock_trigger.py β the Rule's Lambda target. Thin adapter: turn a raw
# device event into a task and hand it to the agent on AgentCore.
import json, os, boto3
agentcore = boto3.client("bedrock-agentcore")
def handler(event, _context):
prompt = (
f"The {event['item']} in fridge {event['deviceId']} is at "
f"{event['level_pct']}%. Restock it if that's the right call."
)
agentcore.invoke_agent_runtime(
agentRuntimeArn=os.environ["AGENT_RUNTIME_ARN"],
runtimeSessionId=event["deviceId"], # per-fridge session β memory
payload=json.dumps({"prompt": prompt, "deviceId": event["deviceId"]}),
)
return {"ok": True}
# agent.py β the brain (AWS Strands Agents). Tools are plain functions;
# the model plans and calls them in a loop until the task is done.
from strands import Agent, tool
import inventory_db, grocery_api, budget, notifications
@tool
def get_inventory(item: str) -> dict:
"""On-hand quantity and reorder threshold for a grocery item."""
return inventory_db.lookup(item)
@tool
def check_price(item: str) -> dict:
"""Live price and availability from the grocery partner."""
return grocery_api.quote(item)
@tool
def within_budget(amount_usd: float) -> bool:
"""True if this purchase keeps the household under its monthly cap."""
return budget.remaining() >= amount_usd
@tool
def place_order(item: str, qty: int) -> dict:
"""Order groceries. Call ONLY after price and budget checks pass."""
return grocery_api.order(item, qty)
@tool
def request_approval(item: str, qty: int, price_usd: float) -> str:
"""Ask the owner to approve a large or unusual purchase before ordering."""
return notifications.ask(f"Approve {qty}x {item} for ${price_usd}?")
@tool
def notify_user(message: str) -> str:
"""Send the household a push notification (via Amazon SNS)."""
return notifications.push(message)
SYSTEM = (
"You restock a smart fridge. When an item is low: check on-hand inventory, "
"get the price, and confirm it fits the monthly budget. Then place the "
"SMALLEST sensible order and notify the user. If the order exceeds $50 or "
"the budget is tight, call request_approval instead of ordering. Never order "
"something already in stock."
)
fridge_agent = Agent(
system_prompt=SYSTEM,
tools=[get_inventory, check_price, within_budget,
place_order, request_approval, notify_user],
)
# app.py β host the Strands agent on Bedrock AgentCore Runtime.
# AgentCore adds serverless scaling, session isolation, memory and identity.
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from agent import fridge_agent
app = BedrockAgentCoreApp()
@app.entrypoint
def invoke(payload):
# runtimeSessionId (the deviceId) keeps each fridge's memory separate
return fridge_agent(payload["prompt"])
app.run() # deploy: agentcore configure && agentcore launch
fridge_device.py reports β iot_rule.sql filters β restock_trigger.py adapts β agent.py decides β app.py hosts it. Each file maps to exactly one stage from section 3.An agent that spends real money from a device trigger is exactly where things go wrong. Four guardrails are non-negotiable.
Risk A low sensor can fire every minute until the shelf is refilled, re-invoking the agent each time.
Fix Dedupe on (deviceId, item, day) with a short-TTL record in DynamoDB or AgentCore Memory; if an open order exists for the item, the agent no-ops. Set the Shadow to ordered so the device stops re-alerting.
Risk A bad price feed or hallucinated quantity drains the grocery budget.
Fix Hard budget cap in within_budget; anything over a threshold routes to request_approval and waits for the owner. The agent can suggest, but a human confirms big spends.
Risk A compromised fridge could publish as other devices or reach systems it shouldn't.
Fix The device's IoT policy is scoped to its own topics (e.g. fridge/${iot:Connection.Thing.ThingName}/*). The agent β not the device β holds the grocery credential, via AgentCore Identity, so device compromise can't place orders directly.
Risk The price API is down, so the agent guesses and orders blindly.
Fix If a required tool fails, the agent notifies the user and stops β it never orders on missing data. Every action is traced (AgentCore observability) for audit.
| Stage | AWS piece | Role in the fridge example |
|---|---|---|
| Sense | Device + IoT Device SDK (MQTT) | Fridge publishes level_pct; updates its Shadow |
| Authenticate | X.509 cert + IoT policy | Per-fridge identity, scoped to its own topics |
| Ingest & route | IoT Core Rules Engine | WHERE level_pct < 10 β invoke trigger |
| Adapt | Lambda (or EventBridge) | Turns the raw event into a task, invokes the agent |
| Reason | Strands agent on AgentCore | Check inventory Β· price Β· budget Β· decide |
| Remember | AgentCore Memory | Monthly spend, open orders, preferences |
| Act | Tools β Grocery API, SNS | Place order (or ask approval), notify owner |
| Close loop | Device Shadow (desired) | Sets milk: ordered; fridge display updates |
Six questions on the integration. Pick an answer for each, then check your score.
Developer guide β MQTT, Device Shadow, and the Rules Engine.
The SDK used for the fridge brain β tools and the model-driven loop.
Runtime, Memory, Identity β where the agent is hosted safely.
Agent Development Kits β pick a different brain (Google ADK, LangGraph) for the same bridge.
The field guide β Lambda, SNS, DynamoDB and the rest, in context.