|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 Corey Bertram |
| 2 | +# SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +"""code.py style example for CircuitPython ESP32 boards. |
| 5 | +
|
| 6 | +Create a secrets.py file on CIRCUITPY with: |
| 7 | +
|
| 8 | +secrets = { |
| 9 | + "ssid": "your-wifi", |
| 10 | + "password": "your-password", |
| 11 | + "datadog_api_key": "your-api-key", |
| 12 | + "datadog_site": "datadoghq.com", |
| 13 | +} |
| 14 | +""" |
| 15 | + |
| 16 | +import time |
| 17 | +import ssl |
| 18 | +import board |
| 19 | +import microcontroller |
| 20 | +import socketpool |
| 21 | +import wifi |
| 22 | +import adafruit_requests |
| 23 | + |
| 24 | +from datadog import DatadogClient |
| 25 | +from secrets import secrets |
| 26 | + |
| 27 | + |
| 28 | +FLUSH_INTERVAL = 60 |
| 29 | +SAMPLE_INTERVAL = 5 |
| 30 | + |
| 31 | + |
| 32 | +print("Connecting to WiFi...") |
| 33 | +wifi.radio.connect(secrets["ssid"], secrets["password"]) |
| 34 | +print("Connected:", wifi.radio.ipv4_address) |
| 35 | + |
| 36 | +pool = socketpool.SocketPool(wifi.radio) |
| 37 | +session = adafruit_requests.Session(pool, ssl.create_default_context()) |
| 38 | + |
| 39 | +default_tags = [ |
| 40 | + "runtime:circuitpython", |
| 41 | + "board:%s" % board.board_id, |
| 42 | +] |
| 43 | + |
| 44 | +client = DatadogClient( |
| 45 | + session, |
| 46 | + secrets["datadog_api_key"], |
| 47 | + site=secrets.get("datadog_site", "datadoghq.com"), |
| 48 | + default_tags=default_tags, |
| 49 | + max_retries=3, |
| 50 | + retry_delay=2, |
| 51 | +) |
| 52 | + |
| 53 | +last_flush = time.monotonic() |
| 54 | + |
| 55 | +while True: |
| 56 | + now = time.monotonic() |
| 57 | + |
| 58 | + client.gauge( |
| 59 | + "circuitpython.cpu.temperature", |
| 60 | + microcontroller.cpu.temperature, |
| 61 | + tags=["source:esp32"], |
| 62 | + ) |
| 63 | + client.gauge("circuitpython.uptime", now) |
| 64 | + |
| 65 | + if now - last_flush >= FLUSH_INTERVAL: |
| 66 | + if not client.flush(): |
| 67 | + print("Datadog flush failed; metrics were dropped") |
| 68 | + last_flush = time.monotonic() |
| 69 | + |
| 70 | + time.sleep(SAMPLE_INTERVAL) |
0 commit comments