BLE Sniffing Apple Find My Python 3 & Bleak OpenHaystack Wireless Telemetry

Building an Apple Find My Network Detector with Python and BLE

Félix Pupo Pérez Félix Pupo Pérez
September 7, 2026
18 min read
Embedded & Wireless Security
fpupoperez/apple_find_my_network_simple_scanner Open Source

Companion open-source repository featuring the asynchronous BLE scanner for Apple Find My and OpenHaystack beacons. Parses manufacturer data payloads, extracts 22-byte public keys, measures signal attenuation (RSSI), and supports prefix filtering.

Python 3.7+ Bleak AsyncIO Cryptography
View on GitHub

Apple's Find My network represents one of the largest and most sophisticated crowdsourced location systems in existence, quietly enlisting over one billion active Apple devices as anonymous Bluetooth Low Energy (BLE) relays. While designed for AirTags and Apple accessories, the security research community spearheaded by the SEEMOO lab unlocked this ecosystem with OpenHaystack—enabling any generic microcontroller or Bluetooth transmitter to tap into this global tracking mesh.

Yet when building custom hardware or evaluating wireless privacy, a fundamental question emerges: how do you independently observe, validate, and sniff these elusive BLE signals in real time? How can you verify that your custom beacon is broadcasting valid Find My frames before deploying it into the wild?

In this technical deep dive, we engineer a high-throughput, cross-platform BLE scanner in Python. Utilizing Bleak and native asyncio concurrency, we deconstruct Apple's proprietary manufacturer advertisement structure, extract the 22-byte elliptic curve public key payload, and parse diagnostic status bytes—without requiring proprietary hardware or jailbroken iOS devices.

Bluetooth Low Energy radio scanner detecting Apple Find My network beacons and OpenHaystack packets
Asynchronous BLE packet sniffing and OpenHaystack public key telemetry in real time

01. Executive summary & system architecture

The detector is built as a zero-friction, modular command-line tool with minimal dependencies. Rather than relying on low-level OS-dependent sockets or complex C++ packet sniffers, it harnesses the modern cross-platform abstraction layer provided by Bleak, combined with an asynchronous stream processor.

The core architecture revolves around three distinct operational stages:

  • Passive Radio Reception: Bleak hooks into the host operating system's native Bluetooth subsystem (CoreBluetooth on macOS, BlueZ / DBus on Linux, Windows Runtime on Windows) in passive scan mode, listening for broadcast advertisements without pairing or initiating connection handshakes.
  • Byte-Stream Filtering & Payload Parsing: The callback pipeline filters advertisements by Apple's Company Identifier (0x004C), inspects the internal sub-type header (0x12 for Find My / OpenHaystack), and performs boundary validation to isolate the 22-byte public key chunk and 1-byte status field.
  • Telemetry Extraction & Key Matching: Detected beacons are formatted with their private/resolvable MAC address, signal attenuation (RSSI in dBm), hex-encoded public key fingerprint, and optional prefix matching for custom tag verification.
Subsystem Runtime / Stack Protocol Role Key Engineering Benefit
Scanner Engine CPython 3.7+ / Bleak BLE GAP Observer (Passive) Cross-platform unified API across Linux, macOS, and Windows without root privileges (on macOS).
Concurrency Model asyncio Event Loop Non-blocking stream processing Zero dropped packets during rapid multi-device bursts; instantaneous terminal I/O flushing.
Payload Engine Pure Python byte manipulation TLV Frame Decapsulation Safe slice indexing against buffer underflows; handles memoryview and bytearray transparently.
Diagnostics & Filter Custom Prefix Byte Matcher Targeted device isolation Eliminates RF ambient noise in dense urban environments populated with hundreds of consumer Apple devices.
Scanner Architecture & Data Pipeline
  ┌────────────────────────┐
  │ Nearby Apple Find My / │
  │ OpenHaystack Beacons   │
  └───────────┬────────────┘
              │ BLE GAP Advertisements (2.4 GHz)
              |
  ┌───────────+───────────────────────────────────────────────┐
  │ Host BLE Adapter (Linux BlueZ / macOS CoreBluetooth / Win)│
  └───────────────────────────┬───────────────────────────────┘
                              │
                              |
  ┌───────────────────────────+───────────────────────────────┐
  │ BleakScanner (Async Callback: callback(device, adv_data)) │
  └───────────────────────────┬───────────────────────────────┘
                              │
          ┌───────────────────┴───────────────────┐
          │ Filter: Company ID == 0x004C (Apple)? │
          └───────────────────┬───────────────────┘
                              │ Yes
                              |
          ┌───────────────────+───────────────────┐
          │ parse_apple_payload(company_id, data) │
          │ - Check Type Byte == 0x12             │
          │ - Validate Payload Length >= 22 bytes │
          └───────────────────┬───────────────────┘
                              │ Valid Find My Beacon
                              |
          ┌───────────────────+───────────────────┐
          │ Match TARGET_PUBLIC_KEY_START prefix? │
          └───────────────────┬───────────────────┘
                              │ Yes (or None)
                              |
  ┌───────────────────────────+───────────────────────────────┐
  │ Formatted Telemetry Console Output (MAC, RSSI, Key, Status│
  └───────────────────────────────────────────────────────────┘

02. Reverse engineering the Apple Find My protocol

To appreciate how this detector works, one must understand how Apple constructs its offline locating architecture. Unlike standard GPS trackers that require expensive cellular subscriptions, power-hungry SIM cards, and satellite positioning, an AirTag or OpenHaystack accessory is fundamentally a cryptographic beacon that broadcasts an advertisement packet into the air.

The beacon itself never calculates its position. Instead:

  1. The tag generates an elliptic curve key pair based on the NIST P-224 (secp224r1) curve.
  2. It periodically broadcasts a truncated 22-byte or 28-byte derivation of its public key over BLE advertisements.
  3. Any nearby iPhone or iPad running iOS detects this broadcast, records its own internal GPS location, encrypts that GPS reading with the beacon's public key, and sends the encrypted blob to Apple's cloud servers.
  4. Only the owner of the private key can query Apple's servers, decrypt the location reports, and plot the coordinates on a map.

Because this communication is broadcast passively over unencrypted BLE advertising channels, any standard Bluetooth radio can intercept and parse the raw transmission.

Privacy Design: Ephemeral MAC Addresses

To prevent physical stalking and surveillance, genuine Apple AirTags constantly rotate their Bluetooth MAC addresses (resolvable private addresses) every few minutes, while also periodically deriving new public keys according to an agreed-upon hash ratchet. Our scanner captures both the current rotating MAC address and the immediate public key payload.

03. BLE advertisement packet anatomy

Standard Bluetooth Low Energy advertisement packets conform to the Generic Access Profile (GAP) specification. An advertisement is composed of a series of Length-Type-Value (LTV) structures. When Apple hardware broadcasts, it utilizes the Manufacturer Specific Data GAP field (type 0xFF).

Inside the manufacturer data payload, Apple structures its proprietary sub-protocols as follows:

Apple Find My Advertisement Frame Specification
Standard BLE GAP Frame:
┌──────────────┬──────────────┬────────────────────────┬─────────────────────────────┐
│ Length (1B)  │ Type: 0xFF   │ Company ID: 0x004C     │ Apple Proprietary Payload   │
│              │ (Mfg Data)   │ (Apple Inc. - 2 Bytes) │ (Variable Length)           │
└──────────────┴──────────────┴────────────────────────┴─────────────────────────────┘

Apple Find My (Type 0x12) Sub-Payload Breakdown:
┌──────────────┬──────────────┬────────────────────────┬─────────────────────────────┐
│ Type Byte    │ Length Byte  │ Status Byte            │ Elliptic Curve Public Key   │
│ 0x12         │ 0x19 (25 B)  │ 0x00 (Battery / State) │ 22 - 28 Bytes               │
└──────────────┴──────────────┴────────────────────────┴─────────────────────────────┘
  Byte 0         Byte 1         Byte 2                   Bytes 3 .. 24+

Let's analyze the exact byte fields:

  • Company ID (0x004C / 76 in decimal): Assigned to Apple Inc. by the Bluetooth SIG. Bleak exposes this as the dictionary key in advertisement_data.manufacturer_data. Note that on the wire, this is transmitted in little-endian format (0x4C, 0x00).
  • Data Type (0x12 / 18 in decimal): Designates the Find My offline finding status beacon. Other Apple types include 0x02 (iBeacon), 0x05 (AirDrop), 0x07 (AirPods audio routing), and 0x10 (Nearby Info).
  • Payload Length (typically 0x19 = 25 bytes): The total byte count of the Find My payload following the type byte.
  • Public Key (22 to 28 bytes): The cryptographic payload. In standard OpenHaystack deployments, the first 22 bytes represent the primary public key identifier used for location matching and server queries.
  • Status Byte: Conveys battery level indicators and device maintenance states (e.g. active tracking vs lost mode).

04. Scanner stack: Python, Bleak & AsyncIO

When working with Bluetooth in Python, developers historically encountered serious friction. Platform-specific libraries like pybluez or direct BlueZ socket bindings required complex compilation, broke across kernel updates, and were completely incompatible with macOS and Windows.

Bleak (Bluetooth Low Energy platform Agnostic Klient) solves this through an elegant, modern architecture:

Operating System Underlying Driver Permissions Required Execution Notes
Linux BlueZ via D-Bus API sudo or bluetooth group Runs seamlessly on Raspberry Pi, x86 servers, and Docker containers.
macOS CoreBluetooth Framework Terminal Bluetooth Permission Zero root privileges needed. Native Apple hardware integration.
Windows Windows.Devices.Bluetooth WinRT Standard User Access Supports native Bluetooth 4.0+ USB dongles and built-in Wi-Fi/BT cards.

Combined with asyncio, Bleak registers an event-driven callback that is executed whenever the radio captures an advertising packet. This prevents blocking the scanner thread, allowing seamless scaling even in RF-congested spaces.

05. Walkthrough: Imports, constants & setup

Let's walk through the script line by line, starting with the header definitions and target filters:

detector.py — Constants & Imports
import asyncio
from bleak import BleakScanner

# APPLE CONSTANTS
APPLE_MANUFACTURER_ID = 0x004C  # 76 in decimal (Assigned by Bluetooth SIG)
FIND_MY_STATUS_TYPE = 0x12      # 18 in decimal: Find My status / OpenHaystack identifier

# OPTIONAL: Put your OpenHaystack public key bytes here (first few bytes or full 22-byte key)
# Example: If your base64 public key decodes to hex, put the hex bytes here to target it.
TARGET_PUBLIC_KEY_START = None  # e.g., bytes([0xAA, 0xBB, 0xCC])

Key design considerations here:

  • APPLE_MANUFACTURER_ID = 0x004C: Bluetooth SIG assigned company ID. Every Apple accessory broadcasts this identifier.
  • FIND_MY_STATUS_TYPE = 0x12: Distinguishes Find My packets from Apple's myriad other protocols (AirDrop, AirPlay, Apple Watch syncing).
  • TARGET_PUBLIC_KEY_START: When debugging a custom hardware prototype (such as an ESP32 running an OpenHaystack firmware), this variable lets you filter out all surrounding public AirTags, zeroing in strictly on your test device.

06. Walkthrough: Payload parsing engine

The core intelligence of the detector resides in parse_apple_payload(). Because raw Bluetooth drivers can deliver buffers as bytes, bytearray, or read-only memoryview instances depending on the OS backend, we enforce defensive conversion before slicing:

detector.py — parse_apple_payload Function
def parse_apple_payload(company_id, data):
    """Parses the manufacturer data to check for Find My / OpenHaystack signatures."""
    if company_id != APPLE_MANUFACTURER_ID:
        return None

    # Force convert to standard bytes to fix indexing issues across backends
    raw_bytes = bytes(data)

    if len(raw_bytes) < 2:
        return None

    data_type = raw_bytes[0]
    length = raw_bytes[1]
    payload = raw_bytes[2:]

    # 0x12 is the Find My / OpenHaystack status type
    if data_type == FIND_MY_STATUS_TYPE:
        # A true Find My beacon payload should be at least 22-23 bytes long
        if len(payload) >= 22:
            public_key = payload[:22]
            status = payload[22] if len(payload) > 22 else None

            return {
                "type": "Find My / OpenHaystack Beacon",
                "public_key_hex": public_key.hex(),
                "status_byte": f"0x{status:02X}" if status is not None else "None"
            }

    return None

Notice the robust safety measures:

  1. Fast-path rejection: If the packet isn't from Company ID 0x004C, it returns None immediately, consuming near-zero CPU cycles.
  2. Minimum length validation: The packet must have at least 2 bytes (Type + Length) to prevent IndexError crashes.
  3. Find My signature verification: Slices the first 22 bytes as the unique cryptographic identifier and conditionally extracts byte 22 as the protocol status flag.

07. Walkthrough: The asynchronous callback

Bleak uses an asynchronous event handler invoked every time a BLE frame is detected in the air. Here is how we extract signal strength and format real-time alerts:

detector.py — callback Function
def callback(device, advertisement_data):
    # Filter only for Apple devices
    if APPLE_MANUFACTURER_ID in advertisement_data.manufacturer_data:
        data = advertisement_data.manufacturer_data[APPLE_MANUFACTURER_ID]
        parsed = parse_apple_payload(APPLE_MANUFACTURER_ID, data)

        if parsed:
            # Check if this is a Find My / OpenHaystack beacon
            if "public_key_hex" in parsed:
                pk_hex = parsed["public_key_hex"]
                rssi = advertisement_data.rssi

                # If you are filtering for a specific custom key
                if TARGET_PUBLIC_KEY_START and not data[2:].startswith(TARGET_PUBLIC_KEY_START):
                    return  # Skip if it doesn't match your specific custom tag

                print(f"[MATCH] Found Find My Tag!")
                print(f"   Address:    {device.address}")
                print(f"   RSSI:       {rssi} dBm")
                print(f"   Public Key: {pk_hex}")
                print(f"   Status Byte: {parsed['status_byte']}\n")
            else:
                # Uncomment if you want to sniff all other Apple traffic (AirPods, iPhones, etc.)
                # print(f"Apple Device ({device.address}) - {parsed['type']} - RSSI: {advertisement_data.rssi}")
                pass

Every detection provides:

  • device.address: The MAC address reported by the operating system.
  • advertisement_data.rssi: The instantaneous Received Signal Strength Indicator in dBm.
  • pk_hex: The 44-character hexadecimal representation of the public key.

08. Walkthrough: Scanning loop & clean shutdown

BLE scanning occupies radio hardware. If a script is abruptly killed without freeing Bluetooth controller resources, subsequent scans can hang or fail. We wrap the main event loop in a strict try ... finally construct:

detector.py — main Coroutine & Entry Point
async def main():
    print("Scanning for Apple and OpenHaystack tags... Press Ctrl+C to stop.")

    # Scanning continuously using a callback function
    scanner = BleakScanner(callback)
    await scanner.start()

    try:
        while True:
            await asyncio.sleep(1)
    except KeyboardInterrupt:
        print("\nStopping scanner...")
    finally:
        await scanner.stop()


if __name__ == "__main__":
    asyncio.run(main())

The await scanner.start() call initializes background radio listening. The while True: await asyncio.sleep(1) cooperatively yields the event loop so incoming BLE interrupts are processed immediately, while scanner.stop() cleanly unregisters the listener when Ctrl+C is caught.

09. Complete standalone script

Here is the complete, production-ready detector.py script ready to save and run on your machine:

detector.py — Full Production Code
import asyncio
from bleak import BleakScanner


# APPLE CONSTANTS
APPLE_MANUFACTURER_ID = 0x004C  # 76 in decimal
FIND_MY_STATUS_TYPE = 0x12      # 18 in decimal: Find My status / OpenHaystack payload identifier

# OPTIONAL: Put your OpenHaystack public key bytes here (first few bytes or full 22-byte key)
# Example: If your base64 public key decodes to hex, put the hex bytes here to target it.
TARGET_PUBLIC_KEY_START = None  # e.g., bytes([0xAA, 0xBB, 0xCC])


def parse_apple_payload(company_id, data):
    """Parses the manufacturer data to check for Find My / OpenHaystack signatures."""
    if company_id != APPLE_MANUFACTURER_ID:
        return None

    # Force convert to standard bytes to fix indexing issues
    raw_bytes = bytes(data)

    if len(raw_bytes) < 2:
        return None

    data_type = raw_bytes[0]
    length = raw_bytes[1]
    payload = raw_bytes[2:]

    # 0x12 is the Find My / OpenHaystack status type
    if data_type == FIND_MY_STATUS_TYPE:
        # A true Find My beacon payload should be at least 22-23 bytes long
        if len(payload) >= 22:
            public_key = payload[:22]
            status = payload[22] if len(payload) > 22 else None

            return {
                "type": "Find My / OpenHaystack Beacon",
                "public_key_hex": public_key.hex(),
                "status_byte": f"0x{status:02X}" if status is not None else "None"
            }

    return None


def callback(device, advertisement_data):
    # Filter only for Apple devices
    if APPLE_MANUFACTURER_ID in advertisement_data.manufacturer_data:
        data = advertisement_data.manufacturer_data[APPLE_MANUFACTURER_ID]
        parsed = parse_apple_payload(APPLE_MANUFACTURER_ID, data)

        if parsed:
            # Check if this is a Find My / OpenHaystack beacon
            if "public_key_hex" in parsed:
                pk_hex = parsed["public_key_hex"]
                rssi = advertisement_data.rssi

                # If you are filtering for a specific custom key
                if TARGET_PUBLIC_KEY_START and not data[2:].startswith(TARGET_PUBLIC_KEY_START):
                    return  # Skip if it doesn't match your specific custom tag

                print(f"[MATCH] Found Find My Tag!")
                print(f"   Address:    {device.address}")
                print(f"   RSSI:       {rssi} dBm")
                print(f"   Public Key: {pk_hex}")
                print(f"   Status Byte: {parsed['status_byte']}\n")
            else:
                # Uncomment the line below if you want to sniff all other standard Apple traffic
                # print(f"Apple Device ({device.address}) - {parsed['type']} - RSSI: {advertisement_data.rssi}")
                pass


async def main():
    print("Scanning for Apple and OpenHaystack tags... Press Ctrl+C to stop.")

    # Scanning continuously using a callback function
    scanner = BleakScanner(callback)
    await scanner.start()

    try:
        while True:
            await asyncio.sleep(1)
    except KeyboardInterrupt:
        print("\nStopping scanner...")
    finally:
        await scanner.stop()


if __name__ == "__main__":
    asyncio.run(main())

10. Telemetry analysis & signal propagation

When running the detector in an active environment, you will observe immediate matches resembling the following:

Terminal Output Telemetry
[MATCH] Found Find My Tag!
   Address:    5A:2B:9C:3D:E1:F0
   RSSI:       -48 dBm
   Public Key: 1a2b3c4d5e6f7890abcdef1234567890abcdef1234567890ab
   Status Byte: 0x00

[MATCH] Found Find My Tag!
   Address:    4F:1A:8E:22:9B:7C
   RSSI:       -74 dBm
   Public Key: 9876543210fedcba0987654321fedcba0987654321fedcba09
   Status Byte: 0x00
Field Observed Value Engineering Interpretation
Address 5A:2B:9C:3D:E1:F0 Randomized BLE private address. Modern iOS devices and AirTags rotate this MAC periodically to prevent physical tracking.
RSSI -48 dBm Received Signal Strength Indicator. -30 to -50 dBm = immediate vicinity (< 2m). -60 to -75 dBm = same room / moderate range. -80 to -95 dBm = fringe boundary.
Public Key 1a2b3c...90ab 44-character hexadecimal representation (22 bytes) of the public key identifying the owner's encrypted record in Apple's cloud.
Status Byte 0x00 Protocol state register. 0x00 represents normal broadcasting state. Non-zero values indicate battery depletion or maintenance states.

11. Real-world use cases

Passive sniffing of Find My beacons serves several practical engineering applications:

Custom Tag Validation

When flashing DIY OpenHaystack firmware on microcontrollers (ESP32, nRF52, Raspberry Pi Pico W), this script provides instant bench verification that the radio is transmitting valid 0x12 frames.

Anti-Stalking Security Auditing

Detect unknown AirTags or tracking accessories traveling alongside you. By monitoring beacon proximity over time, security researchers can identify persistent trackers without waiting for native OS notifications.

RF Environment Surveys

Map out Bluetooth Low Energy propagation and density in public spaces, warehouses, or office facilities by charting RSSI values against spatial physical landmarks.

12. Limitations, security & privacy guardrails

While this scanner is remarkably effective, several protocol-level realities and security constraints must be kept in mind:

  • Passive Observation Only: The script operates purely in passive promiscuous receive mode. It does not transmit, does not connect to peripheral devices, and cannot upload coordinates to Apple servers.
  • Zero Decryption of Location Data: The captured 22-byte public key is merely a public identifier. Without the corresponding private key generated during tag provisioning, it is cryptographically impossible to decrypt where the tag has been.
  • Privacy MAC Address Rotation: Because modern devices change their MAC address every 15 to 60 minutes, you cannot correlate long-term movement across days solely using MAC addresses. Correlating by static OpenHaystack public keys, however, is possible if the DIY beacon does not implement key rolling.
  • Radio Range Bounds: Standard 2.4 GHz BLE operates reliably between 10 and 30 meters indoors. Reinforced concrete, metal enclosures, and human bodies significantly attenuate the signal.
Legal & Ethical Notice

This software and architectural guide are published strictly for educational, testing, and wireless security research purposes. Always respect local radio transmission laws and individual privacy when auditing BLE spectrum.

13. Hardware beacons: MicroPython BLE limits vs. Arduino IDE (tag.ino)

When building hardware transmitters to test your Python detector, developers frequently start with MicroPython on the ESP32. However, in production deployments targeting the actual Apple Find My network, MicroPython encounters severe BLE stack limitations that can truncate or corrupt advertisement packets.

The 31-Byte Ceiling & OpenHaystack Key Fragmentation

A NIST P-224 elliptic curve public key x-coordinate is 28 bytes long. Legacy BLE advertisements have a strict, unforgiving hard ceiling of 31 bytes total for the entire broadcast packet.

To fit inside 31 bytes, OpenHaystack uses a clever key fragmentation scheme: key[6:28] (22 bytes) is packed into the advertisement payload, while the remaining key[0:6] (6 bytes) is encoded into the device's BLE Random Static Address (MAC address) with bits 6 and 7 set to 1 (0xC0).

Why MicroPython's BLE Stack Falls Short

MicroPython's built-in bluetooth.BLE abstraction operates at a high level with two critical bottlenecks:

  1. No Custom Random Static MAC Address API: Standard MicroPython does not expose low-level ESP-IDF GAP functions like esp_ble_gap_set_rand_addr(). Because you cannot set the radio's MAC address to match key[0:6], nearby Apple devices cannot reconstruct the full 28-byte public key. The tag cannot be matched in Find My or OpenHaystack.
  2. Mandatory Flags Overhead & Packet Truncation: MicroPython's ble.gap_advertise() automatically injects standard GAP Flags (0x02, 0x01, 0x06 = 3 bytes). When combined with Apple's 30-byte payload structure (Length + Type + Company ID + Find My header + 22 bytes of key + hint), the total frame reaches 34 bytes, exceeding the 31-byte BLE maximum. As a result, the underlying NimBLE or Bluedroid driver silently truncates or rejects the packet, cutting off the end of your public key or status byte!
Feature / Capability MicroPython (bluetooth.BLE) Arduino IDE / C++ (ESP-IDF GAP)
Raw 31-Byte Payload Truncated (3 bytes consumed by flags) Supported (Exact 31B raw frame via esp_ble_gap_config_adv_data_raw)
Custom Static Random MAC Unsupported (No GAP setter exposed) Supported (Direct esp_ble_gap_set_rand_addr())
Find My Full Matchability Partial / Experimental (Simulated payload only) 100% Genuine OpenHaystack Matchable
ESP32 Core 3.3.x Support N/A (Uses precompiled MicroPython image) Supported with esp32-hal-alloc-ble-mem.h

The Robust Solution: Arduino IDE Reference Implementation (tag.ino)

By leveraging the ESP32 Arduino Core, we bypass high-level constraints and invoke the underlying ESP-IDF GAP APIs directly. This allows installing the first 6 bytes of the public key as the BLE Random Static Address and broadcasting the exact 31-byte raw OpenHaystack frame with microsecond precision.

Below is the complete, tested reference implementation from tag.ino:

tag.ino — ESP32 Arduino Core Reference Implementation
/* tag.ino - Find My offline beacon (Arduino-IDE, ESP32 Arduino core)
 *
 * Generated by the Find My manager on 2026-09-07 14:26
 * Device   : Test (account: Test)
 * Advertisement key (hex): 2caac8a700112233445566778899aabbccddeeff1020304050607080 (sample)
 *
 * Install in the Arduino IDE:
 *   Boards Manager -> install "esp32 by Espressif Systems",
 *   Tools -> Board -> pick your board (a plain ESP32 Dev Module with the
 *   default settings is fine), then Upload.
 *   If btStart() fails at boot, check the Tools -> Board selection, use a
 *   decent USB cable, or lower the Upload speed.
 *
 * A 28-byte key cannot fit inside the 31-byte legacy BLE advertisement, so
 * this uses the OpenHaystack fragmenting scheme (same as the ESP-IDF and
 * MicroPython exports, but complete):
 *   - advertising payload    : key[6:28] + key[0] >> 6 (+ Apple header),
 *   - BLE random static addr : key[0:6] via esp_ble_gap_set_rand_addr.
 * The Arduino core exposes the ESP-IDF GAP API, so the address can be
 * installed here and the tag is Find-My matchable (MicroPython cannot).
 * Since core 3.3.x the core frees the BLE controller/host memory during
 * initArduino() unless a sketch tells it BLE is in use; the
 * esp32-hal-alloc-ble-mem.h include below does that (required when calling
 * the ESP-IDF Bluetooth APIs directly, or btStart() fails on core 3.3.7).
 *
 * Battery: windowed advertising with an active-radio rest between cycles.
 * At a long BEACON_DELAY_S the average current is far below always-on; for
 * true coin-cell life move to a deep-sleep-capable ESP-IDF design.
 */

#include <Arduino.h>
#include <string.h>
#include "esp32-hal-bt.h"
#if __has_include("esp32-hal-alloc-ble-mem.h")
#include "esp32-hal-alloc-ble-mem.h"
#endif
#include "esp_bt_main.h"
#include "esp_gap_ble_api.h"

/* ---------------------- generated device settings ---------------------- */

/* The 28-byte advertisement key (P-224 public x-coordinate).
 * NOTE: Replace the sample bytes with your own key generated via OpenHaystack. */
static const uint8_t public_key[28] = {
    0x2c, 0xaa, 0xc8, 0xa7, /* Beginning prefix (sample format) */
    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
    0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
    0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80
};

/* Advertising window per cycle (seconds). */
#define BEACON_WINDOW_S   10
/* Idle time between cycles (seconds). */
#define BEACON_DELAY_S    300

/* --------------------- beacon layout (OpenHaystack) -------------------- */

/* adv_data[31] = len(30) | 0xff | 0x4c 0x00 | 0x12 0x19 | status 0x00
 *                | key[6:28] (22 B) | key[0] >> 6 | hint 0x00            */
static uint8_t adv_data[31];

/* key[0:6] becomes the BLE random static address (bit 6..7 set => static,
 * bit 0 clear => not multicast). */
static esp_bd_addr_t rnd_addr;

static void set_payload_from_key(void)
{
    const uint8_t *key = public_key;
    adv_data[0] = 0x1E;                 /* advertising data length (30) */
    adv_data[1] = 0xFF;                 /* Manufacturer Specific Data */
    adv_data[2] = 0x4C;                 /* Apple Company ID (0x004C) */
    adv_data[3] = 0x00;
    adv_data[4] = 0x12;                 /* Find My offline type indicator */
    adv_data[5] = 0x19;
    adv_data[6] = 0x00;                 /* Apple Status Byte */
    memcpy(&adv_data[7], &key[6], 22);  /* key[6:28] */
    adv_data[29] = key[0] >> 6;         /* top 2 bits of the key */
    adv_data[30] = 0x00;                /* hint byte */
}

static void set_addr_from_key(void)
{
    memcpy(rnd_addr, public_key, 6);    /* key[0:6] */
    rnd_addr[0] |= 0xC0;                /* random static address marker */
}

static esp_ble_adv_params_t ble_adv_params = {
    .adv_int_min       = 0x140,         /* 200 ms (0x140 * 0.625 ms) */
    .adv_int_max       = 0x140,
    .adv_type          = ADV_TYPE_NONCONN_IND,
    .own_addr_type     = BLE_ADDR_TYPE_RANDOM,
    .channel_map       = ADV_CHNL_ALL,
    .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};

static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
    switch (event) {
    case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT:
        if (param->adv_data_raw_cmpl.status == ESP_BT_STATUS_SUCCESS) {
            esp_ble_gap_start_advertising(&ble_adv_params);
        } else {
            Serial.printf("adv data set failed: %d\n", param->adv_data_raw_cmpl.status);
        }
        break;
    case ESP_GAP_BLE_ADV_START_COMPLETE_EVT:
        if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS) {
            Serial.printf("adv start failed: %d\n", param->adv_start_cmpl.status);
        }
        break;
    default:
        break;
    }
}

static void beacon_cycle(void)
{
    set_payload_from_key();
    /* On completion the gap callback starts advertising. */
    esp_ble_gap_config_adv_data_raw(adv_data, sizeof(adv_data));
    delay(BEACON_WINDOW_S * 1000UL);
    esp_ble_gap_stop_advertising();
    delay((BEACON_DELAY_S - BEACON_WINDOW_S) * 1000UL);
}

static void ble_abort(const char *step)
{
    Serial.printf("%s failed (free heap %u bytes) - stuck here.\n",
                  step, ESP.getFreeHeap());
    Serial.println("Core 3.3.7 frees the BLE memory unless a sketch says");
    Serial.println("BLE is in use; the esp32-hal-alloc-ble-mem.h include in");
    Serial.println("this file fixes that. If it still fails, update the");
    Serial.println("esp32 core in Boards Manager (3.3.8 or newer).");
    while (true) { delay(1000); }
}

void setup()
{
    Serial.begin(115200);

    set_addr_from_key();
    Serial.printf("Find My beacon starting, addr "
                  "%02x:%02x:%02x:%02x:%02x:%02x\n",
                  rnd_addr[0], rnd_addr[1], rnd_addr[2],
                  rnd_addr[3], rnd_addr[4], rnd_addr[5]);

    /* btStart() initializes and enables the BLE controller the way the
     * Arduino core expects (the raw esp_bt_controller_* API is not exposed
     * to sketches). */
    if (!btStart()) { ble_abort("btStart"); }
    if (esp_bluedroid_init() != ESP_OK) { ble_abort("bluedroid init"); }
    if (esp_bluedroid_enable() != ESP_OK) { ble_abort("bluedroid enable"); }
    if (esp_ble_gap_register_callback(esp_gap_cb) != ESP_OK) { ble_abort("gap register"); }
    if (esp_ble_gap_set_rand_addr(rnd_addr) != ESP_OK) { ble_abort("set rand addr"); }

    Serial.printf("beacon loop: %d s window / %d s rest\n",
                  BEACON_WINDOW_S, BEACON_DELAY_S - BEACON_WINDOW_S);
}

void loop()
{
    beacon_cycle();
}

Key Technical Insights from tag.ino

  • Bit Manipulation for Static Random Addresses: In set_addr_from_key(), rnd_addr[0] |= 0xC0 sets the two most significant bits of the address byte to 1. The Bluetooth Core Specification mandates that any random static device address must have its two most significant bits set to 11b. This makes the address valid for BLE controllers.
  • Raw Advertising Configuration: Calling esp_ble_gap_config_adv_data_raw(adv_data, sizeof(adv_data)) passes the raw 31-byte array directly to the controller without encapsulating it in unwanted GAP service structures.
  • Arduino Core 3.3.x Memory Safety: In newer ESP32 Arduino Core releases (v3.3.x), the core automatically frees Bluetooth host memory during initArduino() unless instructed that BLE is in use. Including "esp32-hal-alloc-ble-mem.h" guarantees that the memory heap remains reserved for the Bluedroid stack.
  • Windowed Advertising Duty Cycle: With BEACON_WINDOW_S = 10 and BEACON_DELAY_S = 300, the radio transmits for 10 seconds every 5 minutes. This duty-cycling drastically lowers overall current draw compared to an always-on 40 mA transmitter.

Ultra-Low-Power Optimization: Arduino IDE with ESP32 Deep Sleep (tag_deepsleep.ino)

While the basic windowed loop in tag.ino turns off the radio between cycles, the ESP32 CPU and voltage regulators remain fully energized during delay(), drawing roughly 15–25 mA continuously. For true coin-cell or long-term LiPo battery operation, you must put the ESP32 into Deep Sleep.

During Deep Sleep, the main CPU cores, high-speed RAM, and digital peripherals are powered down completely, leaving only the Ultra-Low-Power (ULP) coprocessor and RTC timer alive. Current draw plummets to ~15–30 µA on bare ESP32 chips (or ~100 µA on development boards with onboard LDOs and USB-UART bridges).

Operating Mode Average Current Estimated Battery Life (1000 mAh LiPo) Estimated Life (CR2032 220 mAh)
Continuous BLE Broadcast ~38 mA ~26 hours < 6 hours
Windowed Rest with delay() ~18 mA ~2.3 days < 12 hours
ESP32 Deep Sleep (10s on / 5m sleep) ~1.3 mA ~32 days ~1 week
ESP32 Deep Sleep (10s on / 15m sleep) ~0.45 mA ~92 days (3+ months) ~3 weeks

Here is the production-ready tag_deepsleep.ino sketch for Arduino IDE. It initializes BLE, broadcasts the 31-byte OpenHaystack payload for 10 seconds, cleanly deinitializes the Bluedroid controller to eliminate quiescent power leakage, and enters deep sleep for 5 minutes:

tag_deepsleep.ino — Arduino IDE with ESP32 Deep Sleep
/* tag_deepsleep.ino - Find My offline beacon with ESP32 Deep Sleep
 *
 * Ultra-low-power battery-optimized firmware for ESP32 / ESP32-S3.
 * Broadcasts Apple Find My advertisement for a short window (10s),
 * powers down all radios, and enters ESP32 deep sleep (~15-30 uA)
 * for the configured interval (5 minutes).
 */

#include <Arduino.h>
#include <string.h>
#include "esp32-hal-bt.h"
#if __has_include("esp32-hal-alloc-ble-mem.h")
#include "esp32-hal-alloc-ble-mem.h"
#endif
#include "esp_bt_main.h"
#include "esp_gap_ble_api.h"
#include "esp_sleep.h"

/* ---------------------- Configuration ---------------------- */

/* The 28-byte advertisement key (P-224 public x-coordinate).
 * NOTE: Replace the sample bytes with your own key generated via OpenHaystack. */
static const uint8_t public_key[28] = {
    0x2c, 0xaa, 0xc8, 0xa7, /* Beginning prefix (sample format) */
    0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
    0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
    0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80
};

/* Advertising duration before sleep (seconds). */
#define BEACON_WINDOW_S      10
/* Deep sleep duration between broadcasts (minutes). */
#define SLEEP_DURATION_MIN   5

/* --------------------- OpenHaystack Beacon Layout -------------------- */

static uint8_t adv_data[31];
static esp_bd_addr_t rnd_addr;

static void set_payload_from_key(void)
{
    const uint8_t *key = public_key;
    adv_data[0] = 0x1E;                 /* advertising data length (30) */
    adv_data[1] = 0xFF;                 /* Manufacturer Specific Data */
    adv_data[2] = 0x4C;                 /* Apple Company ID (0x004C) */
    adv_data[3] = 0x00;
    adv_data[4] = 0x12;                 /* Find My offline type indicator */
    adv_data[5] = 0x19;
    adv_data[6] = 0x00;                 /* Apple Status Byte */
    memcpy(&adv_data[7], &key[6], 22);  /* key[6:28] */
    adv_data[29] = key[0] >> 6;         /* top 2 bits of the key */
    adv_data[30] = 0x00;                /* hint byte */
}

static void set_addr_from_key(void)
{
    memcpy(rnd_addr, public_key, 6);    /* key[0:6] */
    rnd_addr[0] |= 0xC0;                /* random static address marker */
}

static esp_ble_adv_params_t ble_adv_params = {
    .adv_int_min       = 0x140,         /* 200 ms (0x140 * 0.625 ms) */
    .adv_int_max       = 0x140,
    .adv_type          = ADV_TYPE_NONCONN_IND,
    .own_addr_type     = BLE_ADDR_TYPE_RANDOM,
    .channel_map       = ADV_CHNL_ALL,
    .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};

static void esp_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
    if (event == ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT) {
        if (param->adv_data_raw_cmpl.status == ESP_BT_STATUS_SUCCESS) {
            esp_ble_gap_start_advertising(&ble_adv_params);
        }
    }
}

void setup()
{
    Serial.begin(115200);

    set_addr_from_key();
    set_payload_from_key();

    Serial.printf("Woke up. Starting Find My beacon (Addr: %02x:%02x:%02x:%02x:%02x:%02x)...\n",
                  rnd_addr[0], rnd_addr[1], rnd_addr[2],
                  rnd_addr[3], rnd_addr[4], rnd_addr[5]);

    /* 1. Initialize BLE controller & Bluedroid stack */
    if (!btStart()) {
        Serial.println("btStart failed");
        return;
    }
    esp_bluedroid_init();
    esp_bluedroid_enable();
    esp_ble_gap_register_callback(esp_gap_cb);
    esp_ble_gap_set_rand_addr(rnd_addr);

    /* 2. Configure raw advertisement frame & start advertising */
    esp_ble_gap_config_adv_data_raw(adv_data, sizeof(adv_data));

    /* 3. Keep beacon active for the designated capture window */
    Serial.printf("Advertising for %d seconds...\n", BEACON_WINDOW_S);
    delay(BEACON_WINDOW_S * 1000UL);

    /* 4. Cleanly shutdown Bluetooth controller before sleeping to prevent leakage */
    Serial.println("Stopping BLE radio...");
    esp_ble_gap_stop_advertising();
    esp_bluedroid_disable();
    esp_bluedroid_deinit();
    btStop();

    /* 5. Configure RTC Deep Sleep Timer and sleep */
    uint64_t sleep_time_us = (uint64_t)SLEEP_DURATION_MIN * 60ULL * 1000000ULL;
    Serial.printf("Entering deep sleep for %d minutes...\n", SLEEP_DURATION_MIN);
    Serial.flush();

    esp_sleep_enable_timer_wakeup(sleep_time_us);
    esp_deep_sleep_start();
}

void loop()
{
    /* Never reached: device resets into setup() upon deep sleep wakeup */
}

Basic MicroPython Alternative (Bench Prototyping Only)

If you only wish to verify your Python detector on the test bench without genuine Find My key reconstruction, you can still use a simplified MicroPython loop. Keep in mind that the payload may be truncated by the flags overhead:

MicroPython — Simplified Bench Test Transmitter (Truncated Key)
import bluetooth
import time
import machine

# Warning: Standard MicroPython adds flags (0x02, 0x01, 0x06), which may truncate the 31B frame!
def generate_payload(public_key_bytes):
    payload = bytearray()
    payload.extend([0x02, 0x01, 0x06])      # BLE Flags (consumes 3 bytes)
    payload.append(0x1A)                    # Truncated length (26 bytes)
    payload.append(0xFF)                    # Manufacturer Specific Type
    payload.extend([0x4C, 0x00])            # Apple Company ID
    payload.extend([0x12, 0x19])            # Find My type (0x12)
    payload.append(0x00)                    # Status byte
    payload.extend(public_key_bytes[0:20])  # Truncated key chunk to avoid 31B overflow
    return payload

ble = bluetooth.BLE()
ble.active(True)
adv = generate_payload(b'\x00' * 28)
ble.gap_advertise(200000, adv_data=adv, connectable=False)
time.sleep(10)
ble.gap_advertise(None)
ble.active(False)
machine.deepsleep(5 * 60 * 1000)

14. Technical references & specifications

15. License & companion repository

The code and documentation for this project are released under the open-source MIT License. You can clone the companion repository, experiment with custom key matching, and incorporate it into your wireless security toolkit: