08 · Cloud-Integrationen
So senden Sie rbamp-Messwerte an Cloud-Plattformen — AWS IoT Core, Azure IoT Hub, Google Cloud sowie serverlose bzw. verwaltete Observability-Pipelines. Für jede Plattform gibt es ein Python-Setup und die Anweisungen auf Cloud-Seite.
Selbst gehostete DIY-Plattformen (Home Assistant, Node-RED, InfluxDB OSS) — siehe 07 · DIY-Integrationen.
| Cloud | Transport | Authentifizierung | CPython | MicroPython |
|---|---|---|---|---|
| AWS IoT Core | MQTT/TLS | X.509-Zertifikat | paho-mqtt + ssl |
umqtt.simple(ssl=True) |
| Azure IoT Hub | MQTT/TLS | SAS-Token | paho-mqtt + ssl |
umqtt.simple(ssl=True) |
| Google Cloud IoT (eingestellt 2023) | MQTT/TLS | JWT | (Migration — siehe unten) | gleich |
| InfluxDB Cloud | HTTPS-Line-Protokoll | API-Token | requests |
urequests |
| Generischer Webhook / REST | HTTPS-POST | API-Schlüssel | requests |
urequests |
⚠ TLS-Kosten unter MicroPython. Ein TLS-Handshake benötigt etwa 30 kB Heap auf dem ESP32. Auf kleinen Zielen (ESP32-C2) kann es zu einem Speichermangel kommen, wenn WLAN und Puffer parallel laufen. Unter CPython ist das praktisch unproblematisch (Pi 3+/4+ haben 1+ GB RAM).
Für speicherknappe Ziele empfehlen wir eine lokale Mosquitto-Brücke auf einem Pi/SBC: Das MicroPython-Gerät veröffentlicht an mqtts://local-broker (mit minimalem TLS oder ganz ohne TLS im LAN), und die Brücke leitet an den Cloud-Broker über TLS weiter.
TLS-Zertifikate — zwei Vorgehensweisen
CPython — Dateisystempfade
CPython bringt die System-ca-certificates mit (Debian/Ubuntu: /etc/ssl/certs/). Für zusätzliche Gerätezertifikate legen Sie die Dateien neben Ihr Skript und übergeben die Pfade an ssl.SSLContext:
import ssl
ctx = ssl.create_default_context(cafile="/etc/ssl/certs/ca-certificates.crt")
# For mutual TLS (AWS IoT) — add the device cert + key:
ctx.load_cert_chain(certfile="device.cert.pem", keyfile="device.private.key")
MicroPython — in Bytes eingebettet oder Dateisystem
MicroPython hat kein vollwertiges Dateisystem für den TLS-Speicher. Zwei Optionen:
- Eingebettete Bytes — Zertifikatsdateien als Python-Objekte im Skript:
AWS_ROOT_CA = b"""-----BEGIN CERTIFICATE-----
MIIDQTCC...
-----END CERTIFICATE-----
"""
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_verify_locations(cadata=AWS_ROOT_CA)
- Über das Flash-Dateisystem — legen Sie die Zertifikatsdateien auf dem Gerät unter
/lib/certs/ab (permpremote cp) und lesen Sie sie über das Standard-open():
with open("/lib/certs/ca.pem", "rb") as f:
ca_bytes = f.read()
ctx.load_verify_locations(cadata=ca_bytes)
Auf einigen MicroPython-Ports (besonders ESP8266) fehlt ssl.SSLContext — stattdessen wird ein vereinfachtes ussl.wrap_socket(...) mit eingeschränkter Prüfung verwendet. Für Produktionsinstallationen wählen Sie ein Ziel der ESP32-Familie mit vollständigem TLS-Stack.
AWS IoT Core
AWS IoT Core verwendet gegenseitiges TLS mit einem X.509-Gerätezertifikat.
Bereitstellung
- AWS-Konsole → IoT Core → Manage → Things → Create things → Single thing.
-
Zertifikat und Schlüssel erzeugen;
device.cert.pem,device.private.key,AmazonRootCA1.pemherunterladen. -
Hängen Sie eine Richtlinie an, die
iot:Connectundiot:Publishaufarn:aws:iot:erlaubt.: :topic/rbamp/+/state -
Notieren Sie Ihren AWS-IoT-Endpunkt:
xxxxxx-ats.iot...amazonaws.com:8883
CPython-Version (AWS IoT)
import json, ssl, time
from smbus2 import SMBus
import paho.mqtt.client as mqtt_client
from rbamp import RbAmp, RbAmpSensorClass, RbAmpStaleError
AWS_ENDPOINT = "xxxxxx-ats.iot.eu-west-1.amazonaws.com"
AWS_CLIENT_ID = "rbamp-main"
ctx = ssl.create_default_context(cafile="AmazonRootCA1.pem")
ctx.load_cert_chain(certfile="device.cert.pem",
keyfile="device.private.key")
mqtt = mqtt_client.Client(AWS_CLIENT_ID, protocol=mqtt_client.MQTTv311)
mqtt.tls_set_context(ctx)
mqtt.connect(AWS_ENDPOINT, 8883, keepalive=60)
mqtt.loop_start()
with SMBus(1) as bus, RbAmp(bus, 0x50) as dev:
dev.set_sensor_class(RbAmpSensorClass.SCT_013)
dev.set_ct_model(3)
while True:
time.sleep(60)
try:
snap = dev.read_period_snapshot()
except RbAmpStaleError:
continue
payload = {
"voltage": round(dev.voltage, 1),
"power": round(snap.avg_p[0], 1),
"energy": round(dev.energy.wh(0), 3),
"freq": round(dev.frequency, 1),
}
mqtt.publish("rbamp/main/state", json.dumps(payload), qos=1)
MicroPython-Version (AWS IoT)
import time, ujson, ssl
from machine import I2C, Pin
from umqtt.simple import MQTTClient
from rbamp import RbAmp, RbAmpSensorClass, RbAmpStaleError
AWS_ENDPOINT = b"xxxxxx-ats.iot.eu-west-1.amazonaws.com"
# Cert files in `/lib/certs/` (copied over via mpremote cp)
with open("/lib/certs/AmazonRootCA1.pem", "rb") as f:
AWS_ROOT_CA = f.read()
with open("/lib/certs/device.cert.pem", "rb") as f:
DEV_CERT = f.read()
with open("/lib/certs/device.private.key", "rb") as f:
DEV_KEY = f.read()
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.load_verify_locations(cadata=AWS_ROOT_CA)
ctx.load_cert_chain(certfile="/lib/certs/device.cert.pem",
keyfile="/lib/certs/device.private.key")
mqtt = MQTTClient(b"rbamp-main", AWS_ENDPOINT, port=8883,
keepalive=60, ssl=ctx)
mqtt.connect()
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=50_000)
with RbAmp(i2c, 0x50) as dev:
dev.set_sensor_class(RbAmpSensorClass.SCT_013)
dev.set_ct_model(3)
while True:
time.sleep(60)
try:
snap = dev.read_period_snapshot()
except RbAmpStaleError:
continue
payload = ujson.dumps({
"voltage": round(dev.voltage, 1),
"power": round(snap.avg_p[0], 1),
"energy": round(dev.energy.wh(0), 3),
"freq": round(dev.frequency, 1),
})
mqtt.publish(b"rbamp/main/state", payload.encode(), qos=1)
mqtt.ping() # keepalive
Verarbeitung auf der Cloud-Seite
-
Legen Sie eine IoT-Regel an:
SELECT *, topic(2) AS device FROM 'rbamp/+/state'→ Kinesis Data Firehose oder Lambda zur Speicherung. -
Für Dashboards — AWS IoT SiteWise (Industrie-Historian) oder Timestream (Zeitreihendatenbank) → QuickSight.
-
Läuft Home Assistant auf einem Pi und bezieht Daten aus AWS, richten Sie eine lokale Mosquitto-Brücke ein (günstiger und schneller als HA → AWS direkt).
CPython-Alternative — boto3 über die REST-API
Für seltene Veröffentlichungen (einmal pro Stunde oder seltener) können Sie MQTT ganz auslassen und boto3.client('iot-data').publish() verwenden:
import boto3, json
iot = boto3.client("iot-data", region_name="eu-west-1")
iot.publish(topic="rbamp/main/state",
qos=1, payload=json.dumps(payload))
Die Autorisierung erfolgt über die Standardkette der AWS-Anmeldedaten (Umgebungsvariablen / ~/.aws/credentials / IAM-Rolle). Praktisch für die Stapelveröffentlichung per Cron von einem Pi aus. MicroPython hat kein boto3.
Zu den Kosten
Bei Veröffentlichung einmal pro Minute und Gerät ergeben sich bei AWS IoT ~525 k Nachrichten pro Jahr → ~$2.60/Jahr/Gerät im Tarif „Connectivity“ + „Messaging“ (2026, us-east-1). Timestream- und Lambda-Kosten sind separat.
Azure IoT Hub
Azure IoT Hub unterstützt MQTT 3.1.1 über TLS mit SAS-Token-Authentifizierung (einfacher als X.509 für den Heimgebrauch).
Bereitstellung
-
Azure-Portal → IoT Hub → Geräte → Neu → Geräte-ID
rbamp-main, Authentifizierung = Symmetrischer Schlüssel. -
Speichern Sie den Verbindungsstring:
HostName=foo.azure-devices.net;DeviceId=rbamp-main;SharedAccessKey=…. -
Erzeugen Sie ein SAS-Token. Auf CPython über das SDK
azure-iot-deviceoder manuelles HMAC:
import time, hmac, hashlib, urllib.parse, base64
def generate_sas(uri, key, expiry_seconds=3600 * 24 * 365):
expiry = int(time.time()) + expiry_seconds
string_to_sign = urllib.parse.quote_plus(uri) + "\n" + str(expiry)
sig = base64.b64encode(hmac.new(
base64.b64decode(key),
string_to_sign.encode(),
hashlib.sha256
).digest())
return ("SharedAccessSignature "
f"sr={urllib.parse.quote_plus(uri)}"
f"&sig={urllib.parse.quote_plus(sig.decode())}"
f"&se={expiry}")
sas = generate_sas("foo.azure-devices.net/devices/rbamp-main", "BASE64KEY=")
- Auf MicroPython — entweder
ucryptolib+ ein manuelles HMAC (langsam) oder einfach ein 1-Jahres-SAS-Token fest im Code hinterlegen, das auf dem Build-Rechner erzeugt wurde.
CPython-Version (Azure IoT Hub)
import json, ssl, time
import paho.mqtt.client as mqtt_client
AZ_HOST = "foo.azure-devices.net"
AZ_DEVICE = "rbamp-main"
AZ_USERNAME = f"{AZ_HOST}/{AZ_DEVICE}/?api-version=2021-04-12"
AZ_SAS = "SharedAccessSignature sr=...&sig=...&se=..." # see above
ctx = ssl.create_default_context() # Uses the system CAs
mqtt = mqtt_client.Client(AZ_DEVICE, protocol=mqtt_client.MQTTv311)
mqtt.username_pw_set(AZ_USERNAME, password=AZ_SAS)
mqtt.tls_set_context(ctx)
mqtt.connect(AZ_HOST, 8883, keepalive=60)
mqtt.loop_start()
# Inside your 60-second loop:
mqtt.publish(f"devices/{AZ_DEVICE}/messages/events/",
json.dumps(payload), qos=1)
MicroPython-Version (Azure IoT Hub)
from umqtt.simple import MQTTClient
import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
# Azure root CA (Baltimore CyberTrust or DigiCert Global G2):
with open("/lib/certs/azure_ca.pem", "rb") as f:
ctx.load_verify_locations(cadata=f.read())
mqtt = MQTTClient(b"rbamp-main", b"foo.azure-devices.net", port=8883,
user=AZ_USERNAME.encode(),
password=AZ_SAS.encode(),
keepalive=60, ssl=ctx)
mqtt.connect()
# In the loop:
mqtt.publish(b"devices/rbamp-main/messages/events/",
ujson.dumps(payload).encode(), qos=1)
SAS-Token-Ablauf
SAS-Token tragen einen expiry-Anspruch — eine typische Laufzeit reicht von 1 Stunde bis 1 Jahr. Für ein CPython-Deployment verwenden Sie das SDK azure-iot-device; es erneuert das Token selbst. Für MicroPython erzeugen Sie ein 1-Jahres-Token auf dem Build-Rechner und fügen es fest in das Skript ein; alternativ implementieren Sie die HMAC-Erneuerung über ucryptolib.
Verarbeitung auf der Cloud-Seite (Azure)
-
Leiten Sie Nachrichten für hohen Durchsatz an Event Hubs → Stream Analytics → Power-BI-Dashboards weiter.
-
Eine günstigere Alternative: Nachrichten → Storage Account (Blob) → Synapse Serverless SQL für Ad-hoc-Abfragen.
Google Cloud IoT (EINGESTELLT 2023)
Google hat Cloud IoT Core 2023 eingestellt. Migrationswege:
-
Ein MQTT-Broker auf Compute Engine (Sie betreiben Ihren eigenen Mosquitto in einer VM) — dasselbe Muster wie in 07 · DIY-Integrationen, nur mit der öffentlichen IP-Adresse Ihrer VM.
-
HiveMQ Cloud / EMQX Cloud — verwaltete MQTT-Broker, ca. 10–20 $/Monat in Hobby-Tarifen.
-
Pub/Sub über HTTPS — direkt über die REST-API an ein Pub/Sub-Topic veröffentlichen. Unter CPython geht das einfacher über das SDK
google-cloud-pubsubmit einem JSON-Schlüssel eines Dienstkontos:
from google.cloud import pubsub_v1
import json
publisher = pubsub_v1.PublisherClient.from_service_account_json("key.json")
topic_path = publisher.topic_path("my-project", "rbamp")
publisher.publish(topic_path, json.dumps(payload).encode())
Für MicroPython Pub/Sub über HTTPS — siehe den Abschnitt „Generischer Webhook / REST“ unten, wobei Sie den Veröffentlichungsendpunkt von Pub/Sub und ein OAuth-Bearer-Token einsetzen.
InfluxDB Cloud (TLSv1.3 + Line-Protokoll)
InfluxDB Cloud (Serverless-Stufe) nimmt Line Protocol über HTTPS an — dieselbe Form wie der OSS-Pfad in 07 · DIY-Integrationen, aber mit cloud2.influxdata.com als Host und einem API-Token zur Anmeldung.
CPython-Version (InfluxDB Cloud)
import requests, time
from smbus2 import SMBus
from rbamp import RbAmp, RbAmpSensorClass, RbAmpStaleError
INFLUX_URL = "https://us-east-1-1.aws.cloud2.influxdata.com/api/v2/write?org=MyOrg&bucket=energy&precision=s"
INFLUX_TOKEN = "your-rw-token"
def push_influx(u, p, e_wh):
body = f"rbamp,device=main voltage={u:.1f},power={p:.1f},energy={e_wh:.3f}"
try:
r = requests.post(INFLUX_URL, data=body,
headers={
"Authorization": f"Token {INFLUX_TOKEN}",
"Content-Type": "text/plain",
},
timeout=10) # TLS handshake can take up to 3 s
if r.status_code != 204:
print(f"influx HTTP {r.status_code}: {r.text}")
except requests.RequestException as e:
print("influx request failed:", e)
with SMBus(1) as bus, RbAmp(bus, 0x50) as dev:
dev.set_sensor_class(RbAmpSensorClass.SCT_013)
dev.set_ct_model(3)
while True:
time.sleep(60)
try:
snap = dev.read_period_snapshot()
except RbAmpStaleError:
continue
push_influx(dev.voltage, snap.avg_p[0], dev.energy.wh(0))
requests verwendet das System-CA-Bündel — auf einer Standardinstallation von CPython unter Debian/Ubuntu funktioniert das „einfach so“.
MicroPython-Version (InfluxDB Cloud)
import urequests as requests, ujson, ssl, time
from machine import I2C, Pin
from rbamp import RbAmp, RbAmpSensorClass, RbAmpStaleError
INFLUX_URL = "https://us-east-1-1.aws.cloud2.influxdata.com/api/v2/write?org=MyOrg&bucket=energy&precision=s"
INFLUX_TOKEN = "your-rw-token"
# Custom SSL context with embedded CA (DigiCert Global G2)
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
with open("/lib/certs/digicert_g2.pem", "rb") as f:
ctx.load_verify_locations(cadata=f.read())
def push_influx(u, p, e_wh):
body = "rbamp,device=main voltage={:.1f},power={:.1f},energy={:.3f}".format(u, p, e_wh)
try:
r = requests.post(INFLUX_URL, data=body,
headers={
"Authorization": "Token " + INFLUX_TOKEN,
"Content-Type": "text/plain",
})
if r.status_code != 204:
print("influx HTTP", r.status_code)
r.close() # MicroPython socket cleanup
except OSError as e:
print("influx request failed:", e)
Auf den meisten MicroPython-Ports verwendet urequests ein eingebautes CA-Bündel (ohne Prüfung) oder das System-Bündel. Für strikte Prüfung verwenden Sie urequests.post(..., verify=True), sofern Ihr Port das unterstützt; andernfalls gehen Sie über ssl.SSLContext + Low-Level-usocket.
Die kostenlose InfluxDB-Cloud-Stufe (5 GB / 30 Tage Aufbewahrung) deckt etwa 5000 Punkte bei einem Minutentakt pro Tag ab — großzügig für den Heimgebrauch.
Generischer Webhook / REST
Veröffentlichung an einen beliebigen HTTPS-Endpunkt mit API-Schlüssel — funktioniert mit IFTTT-Webhooks, eigenen Flask- / FastAPI-Diensten oder jeder Cloud-Funktion (AWS Lambda / Azure Functions / GCP Cloud Run), die als HTTPS bereitgestellt wird.
CPython
import requests, time, json
WEBHOOK_URL = "https://your-api.example.com/ingest"
API_KEY = "Bearer your-token-here"
def push_webhook(u, p, e_wh):
body = {
"ts": time.time(),
"voltage": u,
"power": p,
"energy": e_wh,
}
try:
r = requests.post(WEBHOOK_URL, json=body, headers={
"Authorization": API_KEY,
}, timeout=10)
if not (200 <= r.status_code < 300):
print(f"webhook HTTP {r.status_code}: {r.text}")
except requests.RequestException as e:
print("webhook failed:", e)
MicroPython
import urequests as requests, ujson, time
def push_webhook(u, p, e_wh):
body = ujson.dumps({
"ts": time.time(),
"voltage": u,
"power": p,
"energy": e_wh,
})
try:
r = requests.post(WEBHOOK_URL, data=body, headers={
"Authorization": API_KEY,
"Content-Type": "application/json",
})
if not (200 <= r.status_code < 300):
print("webhook HTTP", r.status_code)
r.close()
except OSError as e:
print("webhook failed:", e)
Bei niedriger Rate (≤ einmal pro Minute) ist der Aufwand akzeptabel. Bei höheren Raten sollten Sie die Daten auf der Python-Seite bündeln (10 Minuten in einem Ringpuffer sammeln und ein Bulk-JSON veröffentlichen), damit nicht bei jeder Anfrage ein TLS-Handshake anfällt.
Hybrid: lokale Speicherung + Synchronisation in die Cloud
Für Deployments, die Offline-Ausfälle tolerieren: einmal pro Minute lokal protokollieren und einmal pro Stunde in die Cloud übertragen. So überstehen Sie Wi-Fi-Abbrüche und Cloud-Ausfälle ohne Datenverlust.
CPython (rotierende Datei + stündliche Synchronisierung)
import logging, time, csv, requests
from logging.handlers import RotatingFileHandler
from smbus2 import SMBus
from rbamp import RbAmp, RbAmpSensorClass, RbAmpStaleError
log = logging.getLogger("rbamp.csv")
log.setLevel(logging.INFO)
handler = RotatingFileHandler("rbamp.csv", maxBytes=1_000_000, backupCount=5)
handler.setFormatter(logging.Formatter("%(asctime)s,%(message)s",
datefmt="%Y-%m-%dT%H:%M:%S"))
log.addHandler(handler)
def sync_to_cloud_if_due():
"""Once an hour: read rbamp.csv, push the new rows to InfluxDB Cloud."""
# ...uses push_influx from the section above + a state file for the offset...
with SMBus(1) as bus, RbAmp(bus, 0x50) as dev:
dev.set_sensor_class(RbAmpSensorClass.SCT_013)
dev.set_ct_model(3)
last_sync = 0
while True:
time.sleep(60)
try:
snap = dev.read_period_snapshot()
except RbAmpStaleError:
log.warning("stale")
continue
log.info(f"{snap.avg_p[0]:.1f},{dev.energy.wh(0):.4f},"
f"{snap.master_dt_ms}")
if time.time() - last_sync > 3600:
sync_to_cloud_if_due()
last_sync = time.time()
MicroPython (Datei anhängen + Wiederholung beim Verbinden)
import time, ujson
def append_local(snap, dev):
with open("/lib/log.csv", "a") as f:
f.write("{:.0f},{:.1f},{:.4f},{}\n".format(
time.time(), snap.avg_p[0], dev.energy.wh(0),
snap.master_dt_ms))
def sync_if_due():
"""Once an hour: read the accumulated log, push it to the cloud."""
try:
with open("/lib/log.csv") as f:
for line in f:
# ...push_webhook(line) with retry on failure...
pass
# archive successful upload
import os
os.rename("/lib/log.csv", "/lib/log_pushed.csv")
except OSError:
pass # offline / no file yet
Der Akkumulator dev.energy.wh(0) des Pakets zählt während des gesamten Offline-Fensters weiter — es gehen keine Daten verloren, solange der Python-Host mit Strom versorgt bleibt.
Energiebudget (für MicroPython-Batterie-Deployments)
Ein TLS-Handshake ist eine teure Operation: ~3 s + ~30 kB Heap pro Verbindung. Für Deep-Sleep-Szenarien unter MicroPython (siehe 06 · Beispiele, Szenario 9):
-
TLS-Sitzung wiederverwenden über die Wakes hinweg per TLS-Sitzungswiederaufnahme —
umqtt.simpleunterstützt eine persistente Sitzung überclean_session=False, und der Broker merkt sich Ihre Abonnements. -
Stapeln Sie mehrere Messungen im lokalen Flash und veröffentlichen Sie sie pro Wake als einen Bulk-POST — das Muster aus dem Abschnitt „Hybrid“ oben.
-
Der MQTT-Keepalive muss außerhalb von Deep Sleep nicht gehalten werden — das Gerät schläft zwischen den Aufwachvorgängen, und der TLS-Handshake läuft bei jedem Aufwachen (sofern er nicht fortgesetzt wird).
Bei einem Aufwachintervall von 10 Minuten auf einem Li-Ion mit 2000 mAh ist mit etwa 3 Monaten Laufzeit bei Wi-Fi + TLS zu rechnen, gegenüber etwa 6 Monaten bei Wi-Fi + unverschlüsseltem MQTT (siehe Szenario 9).
CPython auf einem Raspberry Pi läuft normalerweise 24/7 an einer Stromversorgung — das TLS-Energiebudget ist nicht kritisch. Für einen Produktivbetrieb mit Optimierung des Stromverbrauchs am Pi siehe 10 · Fehlerbehebung, Abschnitt „Skript hängt / bricht bei Timeout ab“ (eine signalbewusste Schleife für systemctl suspend).
Links
-
06 · Beispiele — die Basisprojekte, auf denen die Cloud-Integrationen aufbauen (insbesondere Szenario 9 „Deep-Sleep-Logger“ und Szenario 10 „asynchrones Streaming“)
-
07 · DIY-Integrationen — selbst gehostete Alternativen
-
10 · Fehlerbehebung — TLS-Handshake / Heap-Budget / Signalbehandlung
Quelle & Issues: rb-amp/rbamp-python · diese Seite im Repo: docs/08_cloud_integrations.md (v1.6.1)