Phone Sync That Survives Reality

A wearable takes one reading a second. You walk out of Bluetooth range for 20 seconds. Without a plan, 20 readings vanish or arrive twice.

Learn how a small device keeps its data safe in flash, numbers every record, resends only what the phone is missing, and fixes its clock afterwards.

Drag the time out of range, then choose a design. Watch which readings reach the phone. Then we build, piece by piece, the log, the numbers, the acknowledgement and the clock.

You need a rough idea of Bluetooth Low Energy (the previous BLE lesson) and how flash memory stores bytes (the flash lesson). We recap both inline.

Built from primary sources: the Bluetooth Core Specification 5.4 (Link Layer, ATT, GATT), the Zephyr FCB and NVS documentation, and the nRF52840 Product Specification. The full list is in the Field Guide. Every device on this page is a model that runs in your browser, not real radio or real flash.

Walk out of range

20 s

Illustrative model: one reading per second for 60 s, out of range from second 18. The link survives a gap shorter than the 4 s supervision timeout (Core Spec 5.4 allows 100 ms to 32 s). The resend design keeps the 30 newest readings in RAM and sends them all on reconnect. The third design keeps every reading in flash and the phone asks for what it lacks.

Chapter 0

Why Phone Sync Is Harder Than It Looks

See the three ways a wearable’s data goes wrong between the device and the app, and name the cause of each

You wear a small band that counts your heart rate once a second. It talks to your phone over Bluetooth, and the phone draws a chart. On a quiet day it works. Then you leave your phone at home and walk to the shop for twenty minutes.

When you come back, the chart has a hole. Twenty minutes is 1,200 readings, and none of them are there. The band was awake the whole time. It measured every second. It just had nowhere to put the numbers.

This is the problem of this lesson. A battery device and a phone are only together some of the time. The device must store what it measures while the phone is away, then forward it when the phone returns. That pattern is called store-and-forward, and the act of catching up is called a sync.

The wearable and the phone

We need two names before we go on. The small device is the wearable. In Bluetooth Low Energy (BLE, the low-power radio from the previous lesson) it is usually the peripheral: it advertises, and the phone connects to it. The phone is the central. One measurement is a reading. When we store a reading together with its bookkeeping bytes, we call it a record.

Try the hero at the top of the page again. It shows 60 readings and a walk out of range. With the first design, anything made while you are away is gone. With the second, the wearable resends its small memory when you return, and some readings arrive twice. Only the third design gets every reading to the phone exactly once. This lesson builds that third design.

Three symptoms, three causes

Engineers who ship wearables see the same complaints again and again. Each complaint points to one cause. Learn to read them, and you can often guess the bug from the chart alone.

A gap in the chart means data was lost: it was sent into a dead link, or it was overwritten before the phone came. A step or a doubled spike means data was repeated: the device sent it again because it could not tell whether the first copy arrived. A reading on the wrong date means the clock was wrong: the device has no idea what day it is. And a record that reads as garbage means it was damaged: power failed in the middle of writing it.

Sort five real-looking complaints below. Pick the cause that explains each one.

Name the cause

Read the complaint from a support inbox. Tap the cause that best explains it. You see the reason, then move to the next one.

The five complaints are illustrative composites written for this lesson. The causes are the four failure families the rest of the lesson fixes, one chapter each.

Why a plain notification is not enough

A first design is easy to write. Each second, the firmware calls the Bluetooth stack to send a notification: a small message the wearable pushes to the phone without being asked. In the Bluetooth specification, a notification is not confirmed by the phone’s app. The next chapter shows exactly what the radio does promise, and where the promise ends.

The fix is not one trick. It is four small habits, each cheap alone. Keep the data in flash until the phone confirms it. Put a number on every record. Let the phone say which number it needs next. And store time as a count since power-up, then fix it up when a phone with a real clock arrives.

The road

  1. What the radio promises: the link layer retries every packet, until the link drops.
  2. How much to keep: bytes per second, hours away, and what fits in RAM and in flash.
  3. The log in flash: append, erase a sector, survive a power cut.
  4. Numbers and cursors: sequence numbers and an acknowledgement that means “I saved up to here”.
  5. Reconnect and drain: how fast a backlog flows back, and how to retry politely.
  6. Clocks: uptime, drift in parts per million, and a boot number.
  7. Break it on purpose: three designs against four disasters.
  8. Field Guide: the numbers, a checklist, the core code and the sources.
A band loses contact with the phone for 2 s, and the link’s supervision timeout is 4 s. What most likely happens to the readings sent during those 2 s?

Chapter 1

What the Radio Promises, and Where It Stops

Follow one packet through retries and acknowledgements, then find the exact moment the promise ends

You post a letter and ask the post office for a signature on delivery. If the neighbour is out, the postman tries again tomorrow. That is a promise with a limit: after a week of failed visits, the letter goes back and the post office stops trying.

Bluetooth Low Energy keeps almost the same promise. While the two devices are connected, every packet is retried until the other side confirms it. When the connection is lost, the retrying stops, and whatever was still waiting is gone. To design a sync, you must know both halves of this promise.

One bit says “I got it”

The retrying happens in the link layer, the part of the Bluetooth controller that owns the radio. The two devices meet at fixed times called connection events. At each event the central sends a packet, and the peripheral answers. The time between events is the connection interval.

How does the link layer know a packet arrived? Each side keeps two one-bit counters. The Core Specification calls them transmitSeqNum and nextExpectedSeqNum. Every packet header carries them as the SN bit (this packet’s number) and the NESN bit (the number I expect next).

Here is the rule, in the specification’s own words, shortened. A new packet is sent with SN set to transmitSeqNum. A resent packet keeps its SN and its payload unchanged. If the NESN in a received packet equals your transmitSeqNum, your last packet was not acknowledged, so you resend it. If it differs, the packet was acknowledged, so you flip transmitSeqNum and send a new one.

One bit is enough because only one packet is ever in doubt. Try it below. Tap a connection event to break it, and watch the same packet go out again.

Break a connection event

Each column is one connection event. Tap a column to cycle it: fine, packet lost, or acknowledgement lost. The wearable sends packets P1, P2 and so on, and the phone keeps each one once.

A simplified model of Core Specification 5.4, Vol 6, Part B, 4.5.9: one packet per event, one-bit SN and NESN, both counters start at zero. Real events can carry several packets and the central also sends data. Packet errors here are chosen by you, not drawn from a radio model.

Look at the column where the acknowledgement is lost. The phone already has the packet. The wearable does not know, so it sends it again with the same SN. The phone sees an SN it did not expect, and throws the copy away. That one-bit check is why the link layer never hands the phone two copies and never skips a packet.

The timer that ends the promise

Retrying cannot go on forever. Both sides run a supervision timer. Every valid packet resets it. If it reaches the supervision timeout without a valid packet, the Core Specification says the connection “shall be considered lost”.

The numbers come from the same specification. The connection interval is a multiple of 1.25 ms from 7.5 ms to 4.0 s. The supervision timeout is a multiple of 10 ms from 100 ms to 32 s. It must be larger than twice the interval times one plus the peripheral latency, where peripheral latency is the number of events the peripheral may skip when it has nothing to say (at most 499).

Take a worked example. The interval is 30 ms. The timeout is 4 s. You walk out of range at second 18. The wearable listens at every event, and nothing arrives. After 4,000 / 30, about 133 events, the timer expires. Until then the controller keeps retrying the same queued packets. At 4 s the link is declared lost, and the controller drops whatever it still holds.

Race the supervision timer

The bar is your time out of range. The line is the supervision timeout. If the bar ends before the line, the packets queued in the controller are delivered late. If it ends after, they are dropped.

6 s

The interval and timeout choices are legal values from Core Spec 5.4 (7.5 ms to 4 s, and 100 ms to 32 s). The model counts missed events as the gap divided by the interval and ignores peripheral latency and clock tolerance. A phone, not your firmware, usually has the final say on the parameters.

On real hardware. nRF52840 DK running a Zephyr peripheral that notifies once per second, and a phone with a Bluetooth logging app. Walk out of range, or put the phone in a closed metal tin, then back. Measure the time from the last received notification to the disconnect event, and compare it with the supervision timeout you requested.

Above the radio: what a notification is

The link layer protects each packet. The next layer up, the Attribute Protocol (ATT), decides what the packet means. The wearable exposes values as attributes. It pushes a new value with a notification, or with an indication.

A notification has no reply from the phone’s application. An indication does: the phone must send a confirmation before the wearable may send the next indication on that connection. Zephyr’s documentation says the same in its own words: notify is a permission “without acknowledgment”, indicate is “with acknowledgment”.

The size limit comes from the default ATT_MTU, the largest ATT packet. On LE the default is 23 bytes. A notification spends 3 of them on its opcode and handle, so Zephyr’s header states the value is limited to ATT_MTU minus 3. That leaves 20 bytes at the default.

One more warning: a notification has no confirmation, and a stack that runs out of buffers can drop one. Treat notifications as unreliable. Zephyr’s bt_gatt_notify_cb calls your callback once the notification has been sent. That means it left your queue. It does not mean the phone’s app saved it.

c/* Ask for a 30 to 50 ms interval, no skipped events, a 4 s supervision timeout.
   Units: interval 1.25 ms, timeout 10 ms (Zephyr conn.h). 24 * 1.25 = 30 ms. */
static const struct bt_le_conn_param want = BT_LE_CONN_PARAM(24, 40, 0, 400);
int err = bt_conn_le_param_update(conn, &want);   /* a request; the central decides */

/* Largest notification value right now: ATT_MTU - 3 (default MTU 23 gives 20) */
uint16_t room = bt_gatt_get_mtu(conn) - 3;
The wearable sends a packet and the phone receives it, but the acknowledgement is lost. What does the one-bit SN scheme do?

Chapter 2

How Much Should the Wearable Keep?

Turn “the phone might be away for a while” into bytes, and choose between RAM, flash and thinner data

A shop keeper goes to lunch and leaves a notebook by the till. Customers write their orders in it. How many pages does the keeper need? The answer depends on three things: how many customers come each hour, how many lines each order takes, and how long lunch lasts.

A wearable has the same question. The notebook is memory. The customers are readings. Lunch is the time the phone is away. If you guess the pages first and the numbers later, you will either lose data or pay for memory you never use.

Bytes per second, then bytes per hour

Start with one record. Suppose each second the wearable stores a sequence number (4 bytes), a timestamp counter (4 bytes), a boot number (2 bytes, Chapter 6), two measurements such as heart rate and motion (4 bytes) and status flags (2 bytes). That adds up to 16 bytes, which is exactly four 32-bit words.

Flash needs a little extra. Zephyr’s flash circular buffer (FCB) stores, for every entry, its length, its data and a checksum over the data. The documentation does not give the sizes of those fields, so we budget 8 bytes of overhead. We call the record plus its overhead an entry. Our entry is 24 bytes. This is a budgeting choice for this lesson, not a number from the manual.

Now the arithmetic. One entry per second is 24 bytes per second. One hour is 3,600 seconds, so 86,400 bytes, about 84 KB. A full day is 24 times that: 2,073,600 bytes, near 2 MB. A day of one-per-second records does not fit in the 1 MB of flash on an nRF52840, which is the part we use as our example.

Size the notebook

Pick how often the wearable stores a reading, how big a record is, and how long the phone is away. Three bars share one log scale. The yellow bar is what you need. Compare it with each budget.

16 B
12 h

Illustrative budgets: 32 KB of RAM for a ring, 512 KB of the 1 MB nRF52840 flash for the log, and 8 bytes of per-entry overhead in flash. The nRF52840 has 1 MB flash and 256 KB RAM. Real values depend on your bootloader, settings area and firmware size.

On real hardware. nRF52840 DK. Open the devicetree flash partition that holds your log, read its size in bytes, and divide by your real entry size. Then let the board run and note when the first sector is erased. Compare that time with the Size the notebook read-out.

Read the bars as three questions. Does a few minutes fit in RAM? Does a night fit in flash? What happens at a rate of 50 per second? The answers are a design input, so write them down before the first line of code.

RAM or flash?

RAM is fast, and writing it costs almost no energy. But it forgets everything at a reset or when the battery browns out. Flash keeps its contents without power, which is the point of a log. It costs more per write, and it can only be erased in big blocks.

Here are the nRF52840 numbers from its product specification. Writing one 32-bit word takes 41 microseconds. Our 24-byte entry is six words, so about 246 microseconds. Erasing one page takes 85 milliseconds. A page holds 4 kB, so it stores 170 entries of 24 bytes, which is 170 seconds of one-per-second data. The erase happens once in those 170 seconds.

So the cost of flash is small in energy and in time, but the 85 ms erase is long next to a 30 ms connection interval. You should plan when it happens. A common plan is a small RAM buffer that collects a page of entries, then one burst of writes. Chapter 3 shows how a log survives the erase and a power cut.

Three ways to fit

When the notebook is too small, you have three levers. You can add memory: a serial NOR flash chip next to the microcontroller adds megabytes, at the cost of board area and a bus. You can shrink the data: store a 16-byte summary each minute instead of each second, which cuts the byte rate by 60 times. Or you can choose what to forget.

That third lever matters most, because every log fills in the end. A ring overwrites the oldest data, so you always keep the most recent hours. A stop-when-full log refuses new data and keeps the oldest. For a fitness wearable you usually want the ring. For an audit trail you may want the opposite. The Zephyr FCB documentation puts the choice in your hands: erase the oldest block, or stop writing until the data is collected.

Whichever you choose, make the loss visible. If the ring overwrites records 1 to 500 while the phone is away, the phone should learn that 500 records are gone, not just that the numbers jump. Chapter 4 does this with sequence numbers.

c/* One record: 16 bytes, four 32-bit words. Fixed size keeps the log simple. */
struct record {
    uint32_t seq;        /* 0, 1, 2 ... never reused (Chapter 4)        */
    uint32_t ticks;      /* milliseconds since this boot (Chapter 6)    */
    uint16_t boot_id;    /* which power-up made the ticks (Chapter 6)   */
    uint16_t hr_bpm;     /* the measurement                              */
    uint16_t motion;     /* a second measurement                         */
    uint16_t flags;      /* sensor status, version, reserved            */
};
_Static_assert(sizeof(struct record) == 16, "record must stay 16 bytes");
A wearable stores one 16-byte record per second and Zephyr-style flash adds 8 bytes per entry. About how long does a 512 KB log hold?

Chapter 3

The Log in Flash

Append records, reclaim old sectors, and lose power in the middle of a write without losing the log

A paper notebook has one great property: you can write on a new line without touching the old ones. If someone knocks the pen halfway through a word, only that word is ruined. A flash log should work the same way. Add at the end. Never edit the middle. Make a half-written line easy to spot.

The flash lesson built the physics. We use three facts from it, with the nRF52840 numbers from its product specification. You can write only whole 32-bit words. Each word may be written twice before an erase. And an erase clears a whole page, which takes 85 ms.

Why append-only fits flash

Flash cells start as all ones. A write can turn a one into a zero, but never a zero back into a one. Only an erase resets a block to ones. A log that only appends never needs to turn a zero back, so it never erases until it must reclaim space.

Erasing works on a whole sector, the smallest erasable block. On the nRF52840 the erase unit is a 4 kB page. So the log is a ring of sectors. The head fills one sector from start to end, then moves to the next. When all sectors are used, the oldest sector must be erased before the head can wrap around to it.

Each entry guards itself

How do you know a record was written completely? You write it so that the last thing to land is proof. Zephyr’s flash circular buffer (FCB) stores each entry as its length, its data and a checksum over the data. The sequence in code is three calls: ask for space, write the data, then finish. Finishing computes the checksum and completes the entry.

A checksum is a small number computed from the data. If the data changes, the number almost always changes too. When the battery dies during the write, the data is half there and the checksum is missing or wrong. On the next boot the reader sees the mismatch and skips the entry. The Zephyr page says entries with invalid checksums are skipped, and that this is how incomplete writes are detected.

Try the log below. Arm a power cut, append a record, and see the torn slot. Then reboot the device and watch it recover its place.

Fill the log, cut the power

Each row is a sector of eight slots. Append records, arm a power cut for the next write, let the phone acknowledge, and reclaim the oldest sector. Pick what happens when the log is full.

A model, not real flash. Six sectors of eight slots stand in for the 128 sectors of a 512 KB log. The checksum check is simulated: a torn slot is simply marked invalid. The erase count per sector shows wear; on the nRF52840 each page is specified for 10,000 erase cycles.

On real hardware. nRF52840 DK. Toggle a GPIO pin high around the sector erase and read the pulse on a logic analyser: the product specification gives 85 ms per page. Then remove power during an append, reboot, and confirm the scan skips the torn entry and reuses its sequence number.

Two things deserve a second look. First, after a power cut the torn slot stays in the log, but the next record is numbered by scanning for the newest valid entry. The torn record’s number is reused. Second, the sequence number lives in the record itself, so a reboot recovers it from flash. It is never a RAM-only counter.

Reclaiming a sector

You may erase a sector only when every record in it is safe elsewhere. In this design, “safe” means the phone has confirmed it. So the firmware keeps one number: the highest sequence the phone has acknowledged. A sector whose newest record is at or below that number can be reclaimed.

If the phone never confirms, the ring policy overwrites unconfirmed data when it must. The stop policy refuses new data instead. Either way, count what you dropped. Chapter 4 uses that count to tell the phone about the gap.

The erase blocks the flash for 85 ms. That is almost three 30 ms connection intervals. Reclaim after you finish a sync, or when the radio is idle, and never in the middle of a burst.

How long will it last?

Now use the endurance figure. A 512 KB log is 128 sectors of 4 KB. At 24 bytes per second, a sector fills in about 170 s, so one lap of all 128 sectors takes about 21,800 s, which is 6.07 hours. Each sector is therefore erased close to four times a day.

The specification says 10,000 erase cycles per page. 10,000 divided by four a day is about 2,500 days, near 6.9 years. That works because the ring spreads erases evenly. If you wrote every record to the same sector, it would be erased once every 170 s, and it would reach 10,000 cycles in 19.7 days. This is the whole case for wear levelling: spread the erases.

c/* Append one record to a Zephyr flash circular buffer.
   fcb_append reserves space, we write the data, fcb_append_finish adds the checksum. */
static int log_append(const struct record *r)
{
    struct fcb_entry loc;
    int rc = fcb_append(&log_fcb, sizeof(*r), &loc);
    if (rc == -ENOSPC) {                 /* out of space: your policy decides      */
        if (policy == STOP_WHEN_FULL) return rc;
        dropped += entries_in_oldest_sector();   /* remember what the ring throws away */
        rc = fcb_rotate(&log_fcb);              /* erase the oldest sector (85 ms)       */
        if (rc) return rc;
        rc = fcb_append(&log_fcb, sizeof(*r), &loc);
    }
    if (rc) return rc;
    rc = flash_area_write(log_fcb.fap, FCB_ENTRY_FA_DATA_OFF(loc), r, sizeof(*r));
    if (rc) return rc;
    return fcb_append_finish(&log_fcb, &loc);   /* checksum last: proof of a whole write */
}

/* On boot: the next sequence number comes from flash, never from RAM. */
static int scan_cb(struct fcb_entry_ctx *ctx, void *arg)
{
    struct record r;
    flash_area_read(ctx->fap, FCB_ENTRY_FA_DATA_OFF(ctx->loc), &r, sizeof(r));
    uint32_t *next = arg;
    if (r.seq >= *next) *next = r.seq + 1;
    return 0;
}
fcb_walk(&log_fcb, 0, scan_cb, &next_seq);       /* the walk skips entries with bad checksums */
The battery dies while the firmware writes record 57. After reboot, how should the firmware pick the next sequence number?

Chapter 4

Numbers and Cursors: Send Only What Is Missing

Give every record a number, let the phone say how far it has saved, and make repeats harmless

Two friends move house by passing numbered boxes across a fence. Box 1, box 2, box 3. One friend calls out, “I have everything up to box 7.” Now the other knows what to pass next. No box is passed twice on purpose. If a box does come twice, the label tells you to ignore the copy.

That is the whole idea of this chapter. The label is a sequence number. The call from the fence is a cumulative acknowledgement. Together they turn an unreliable stream into a sync that survives the walk out of range.

Why a number fixes both loss and repeats

Without numbers, the phone sees a stream of values. A missing value leaves no trace. A repeated value looks like a new one. The phone cannot tell, and neither can you.

With a number in every record, both problems become visible. If the phone holds 101, 102 and 104, it knows 103 is missing. If it receives 102 again, it sees the number is already stored and ignores the copy. A receiver that gives the same result however many times it sees a record is called idempotent. Idempotence is the cheapest way to make a retry safe.

Delivery has three standard flavours. At most once means send and forget: no repeats, but loss is possible. At least once means resend until confirmed: no loss, but repeats are possible. Exactly once is what you want. You build it as at-least-once on the wire plus an idempotent receiver. The repeats still happen on the wire, but they change nothing.

How many bits does the number need? A 32-bit counter holds 4,294,967,296 values. At one record per second it lasts 136 years. At 50 records per second it lasts about 2.7 years. At 1,000 per second it lasts only 49.7 days. Pick the width from the fastest rate and the longest life you expect.

The cursor: one number that says how far you have saved

Acknowledging every record one by one is expensive. Each reply costs radio time and energy. Instead, the phone sends one number: the cursor, the highest sequence such that it has saved every record from the oldest up to it, with no gaps. This is a cumulative acknowledgement.

Take a worked example. The phone has saved 1 to 102, plus 104 and 105. Its cursor is 102, not 105, because 103 is missing. It writes 102 to the wearable. The wearable may now free everything up to 102, and next time it sends from 103. It sends 104 and 105 again; the phone sees them as repeats and ignores them. The cost is two wasted notifications. The gain is that the phone never has to describe its holes.

The order that matters: save, then acknowledge

The most dangerous line in the protocol is the order of two actions on the phone. If the app saves the records and then writes the cursor, a crash between them only causes a resend. If it writes the cursor first, a crash between them loses data for good: the wearable has already freed those records.

Try it. Run a few rounds with some packet loss. Then switch to “Ack, then save”, kill the app during a round, and look at the red cells.

Sync with a cursor

Top row: the wearable’s 24 records. Middle row: what the phone has saved. Each round sends up to 8 records starting just after the phone’s cursor. Raise the loss, run rounds, and watch the cursor advance.

30%

A model of this lesson’s own sync design, not a Bluetooth standard. Packet loss is drawn from a seeded random generator. The acknowledgement is assumed to arrive, since a write with response is confirmed by ATT. The crash happens after the phone has received the round and before it has saved it.

On real hardware. nRF52840 DK and a small phone script. Toggle airplane mode on the phone during a sync, then compare two sets: the sequence numbers the wearable wrote, and the keys in the phone database. They must match with no holes and no repeated key. Repeat with the early-acknowledge bug and count the missing records.

The shape of the protocol

Four attributes are enough. A status value the phone can read: the oldest and newest sequence on the wearable, a boot number (Chapter 6) and a count of records dropped. A control value the phone writes: “send from sequence S, at most C records”. A data value the wearable notifies, one or more whole records each time. And an acknowledge value the phone writes, with response, holding the cursor.

Why a write with response for the cursor? Because ATT confirms it. The wearable can trust that the number arrived. For the bulk data, notifications are fine, because a lost record is simply asked for again. The cursor, not the notification, is what carries reliability.

The status read also handles overwritten data. If the wearable’s oldest sequence is greater than the cursor plus one, then records in between are gone. The phone writes them down as a known gap and moves its cursor past them. You lose data, but you know exactly how much, and the chart can show the hole honestly.

c/* Wearable: send records [from, from+count) as notifications. 16 bytes fits ATT_MTU - 3. */
static void send_range(struct bt_conn *conn, uint32_t from, uint32_t count)
{
    for (uint32_t s = from; s < from + count && s <= newest_seq; s++) {
        struct record r;
        if (log_read(s, &r)) continue;                  /* gone: the ring overwrote it      */
        if (bt_gatt_notify(conn, data_attr, &r, sizeof(r))) break; /* queue full or link gone: stop */
    }
}

/* Wearable: the phone writes its cursor. Never move backwards; free what is safe. */
static ssize_t on_ack(struct bt_conn *c, const struct bt_gatt_attr *a,
                      const void *buf, uint16_t len, uint16_t off, uint8_t flags)
{
    uint32_t cursor;
    if (len != 4) return BT_GATT_ERR(BT_ATT_ERR_INVALID_ATTRIBUTE_LEN);
    memcpy(&cursor, buf, 4);
    if (cursor > newest_seq) return BT_GATT_ERR(BT_ATT_ERR_VALUE_NOT_ALLOWED);
    if (cursor > acked_seq) { acked_seq = cursor; reclaim_sectors_up_to(acked_seq); }
    return len;
}
python# Phone: one sync. Save first, then acknowledge. (pseudocode for any BLE library)
def sync(dev):
    st = dev.read(STATUS)                              # oldest_seq, newest_seq, boot_id, dropped
    cursor = db.cursor(dev.id, st.boot_id)             # highest contiguous seq already saved
    if st.oldest_seq > cursor + 1:
        db.mark_gap(cursor + 1, st.oldest_seq - 1)  # the ring overwrote these: a known gap
        cursor = st.oldest_seq - 1
    while cursor < st.newest_seq:
        dev.write(CONTROL, from_seq=cursor + 1, count=64)
        got = dev.collect_notifications(timeout=2.0)
        db.insert_or_ignore(got)                       # key (boot_id, seq): repeats change nothing
        db.commit()                                    # 1. SAVE
        new = db.highest_contiguous(cursor)
        if new == cursor: raise Retry()                 # nothing new arrived: back off (Chapter 5)
        cursor = new
        dev.write_with_response(ACK, cursor)           # 2. THEN ACKNOWLEDGE
The phone has saved records 1 to 102 and also 104 and 105. What cursor does it send, and why?

Chapter 5

Reconnect, Drain and Retry Politely

Estimate how long a backlog takes to flow back, choose connection settings for the sync, and back off when it fails

You walk through the door after six hours at work. The phone and the wearable notice each other. A backlog of 21,600 records, one for every second you were away, is waiting in flash. How long before the app shows your day?

If the answer is eleven minutes, the app feels broken. If the answer is eleven seconds, it feels like magic. The records and the radio are identical in both cases. Only the settings differ. This chapter shows which settings.

Getting back together

After a disconnect, the wearable does one thing: it goes back to advertising, the way it did before the first connection. After a link loss, a peripheral goes back to a connectable advertising mode so the client can re-establish the connection. The phone decides when to reconnect. A phone app can keep a background connection request open for a known device, so the link returns on its own when the wearable is heard.

You do not write reconnect logic on the wearable. You write two policies. The first is how fast to advertise while a backlog exists, because a slower advertising rate saves energy but delays the reunion. The second is what to do once connected: speed up, drain, then slow down.

The pipe has three widths

Think of the radio as a pipe with three widths multiplied together. First, how many records fit in one notification. Second, how many notifications fit in one connection event. Third, how many connection events happen each second.

The first width comes from the MTU. A notification carries at most ATT_MTU minus 3 bytes. At the default MTU of 23 that is 20 bytes, so only one 16-byte record fits, and 4 bytes are wasted. At an MTU of 247 that is 244 bytes, so 15 records fit, with 4 spare. The phone and wearable agree the MTU with an exchange when they connect. It is requested once per connection.

The second width is how many packets the controller sends in one event. The Nordic SoftDevice Controller documentation gives one upper figure: on the LE 2M PHY, eleven 27-byte packet pairs fit in one 7.5 ms event. In practice the number is lower and depends on both chips. We treat it as a slider. The third width is the connection interval. A short interval gives more events per second, at the cost of more energy.

Now the worked example. Records per notification: 1. Notifications per event: 1. Interval: 30 ms. Time to drain 21,600 records: 21,600 events times 30 ms, which is 648 s, about 10.8 minutes. Change the MTU to 247 and send 4 notifications per event: 60 records per event, 360 events, 10.8 s. Shorten the interval to 7.5 ms and, if four notifications still fit in the shorter event, it takes 2.7 s.

Drain the backlog

The backlog is one 16-byte record per second. Set the MTU, the notifications per event and the interval. The yellow bar is your time to drain. The grey bar is the default setting, MTU 23, one notification per event, 30 ms.

6 h
1

Illustrative model: records per notification is the whole number of 16-byte records that fit in MTU minus 3; notifications per event is your choice, since the real number depends on both radios; no retransmissions or phone-side delays are included. Intervals are legal values from Core Spec 5.4.

On real hardware. nRF52840 DK. Log the time from connection to a cursor equal to the newest sequence, first at the default MTU of 23 and then after an MTU exchange and a faster interval request. Put both times next to the Drain the backlog bars.

Look at what moved the answer most. Packing records into a bigger MTU gave 15 times more records per notification. Allowing more notifications per event gave another few times. The interval is the third lever, and it is the one you cannot set alone. The central makes the final choice, so you send a request and read back what you got.

Sync fast, then idle slow

A short interval keeps the radio busy, so it drains the battery. A long interval keeps the device asleep, so it saves energy but makes a sync slow. The usual answer is both. When a backlog exists, ask for a short interval, drain, then ask for a long one. The lesson on the coin-cell year puts numbers on the energy cost.

Flow control matters too. If you call bt_gatt_notify faster than the radio can send, the stack’s buffers fill and calls fail. Do not loop and retry at once. Send a window of records, wait for the sent callback of the last one, then send the next window. Chapter 4’s rounds of 8 or 64 records are exactly such windows.

When a sync fails, wait before trying again

Suppose the phone tries to sync at the edge of range and every attempt fails. If the phone retries at once, again and again, it burns its own battery and keeps the wearable awake. A better habit is exponential backoff: wait 1 s after the first failure, 2 s after the second, 4 s after the third, doubling up to a cap. Add jitter, a small random change, so two phones or two apps do not retry in step.

Backoff is safe here for a reason from Chapter 4. A round that fails halfway has already saved its records and moved the cursor. The next attempt continues from there. Nothing is repeated, and nothing is lost.

c/* Ask for a fast link while a backlog drains, a slow one afterwards.
   Interval units are 1.25 ms and timeout units are 10 ms (Zephyr conn.h).
   Rule from the Core Spec: timeout must exceed 2 * (1 + latency) * interval. */
static const struct bt_le_conn_param fast = BT_LE_CONN_PARAM(6, 12, 0, 400);   /* 7.5 to 15 ms, 4 s timeout */
static const struct bt_le_conn_param slow = BT_LE_CONN_PARAM(800, 800, 0, 600); /* 1000 ms, 6 s timeout > 2 s */

void on_backlog_start(struct bt_conn *c) { bt_conn_le_param_update(c, &fast); }
void on_backlog_done(struct bt_conn *c)  { bt_conn_le_param_update(c, &slow); }
pythonimport random

def next_delay(attempt, base=1.0, cap=60.0):
    d = min(cap, base * 2 ** attempt)         # 1, 2, 4, 8 ... up to 60 s
    return random.uniform(d / 2, d)             # jitter: half to full delay
A backlog of 21,600 records drains at one 16-byte record per notification, one notification per event, 30 ms interval. About how long does it take?

Chapter 6

Clock Reconciliation: What Time Was That Reading?

Stamp readings with a count since power-up, then turn the count into a real date, even after drift and reboots

Picture a stopwatch with no calendar. You press start when you wake up, and it counts seconds. It can say “this happened 9,200 seconds after I started”. It cannot say what day that was. A wearable is that stopwatch. The phone is the one with the calendar.

So the sync has a second job beyond moving bytes. It must line the two clocks up, and keep them lined up when the stopwatch runs a little fast or slow, or gets reset.

Count first, name the date later

The wearable has a timer that counts milliseconds since the last boot. We call the count uptime or ticks. Every record stores its ticks at the moment of the measurement. This is cheap, it needs no phone, and it works with no connection for weeks.

Later, when the phone is connected, they run a small exchange. The phone reads the wearable’s ticks right now, and notes its own wall clock at the same instant. The pair is an anchor: “device tick 4,820,000 was 09:14:03.250 UTC”. The difference between the two clocks is the offset. A record with ticks t then has wall time t plus the offset.

The word later is the trick. The conversion happens at the phone, after the fact. That is called late binding of time. A record never has to carry a date, so it never carries a wrong one.

How exact is one anchor? The read travels over a connection event, and the answer waits for the next one. The phone can only say the time lies between when it sent the request and when it heard the answer. Half that round trip is the error bar. With a 30 ms interval, expect tens of milliseconds. Taking several anchors and keeping the one with the shortest round trip tightens it.

The crystal runs a little fast

Every clock counts oscillations of a crystal. No crystal is exact. Its error is given in parts per million (ppm): 20 ppm means 20 extra ticks in every million. That sounds like nothing, so do the arithmetic. A day has 86,400 s. Multiply by 20 / 1,000,000 and you get 1.728 s per day. After 10 days the clock is 17.28 s off. After 30 days, 51.8 s.

Looser clocks are worse. The Nordic controller documentation uses 250 ppm and 500 ppm in its timing examples, and 500 ppm is 43.2 s per day. A heart-rate chart that is 17 s off hardly matters. A wearable that must line up with a camera or another sensor cares a great deal, as the clocks and drift lesson shows.

Try the model below. Set the clock error, then compare three ways to convert ticks into time.

Drift against anchors

The x axis is 30 days. The line shows how many seconds wrong a record’s time is, depending on when it was made. Vertical ticks mark the days the phone synced. Choose how the phone converts ticks.

+20 ppm
10

The drift line is exact arithmetic: error = ppm / 1,000,000 times elapsed seconds. The fit strategy leaves a small residual that is illustrative (about 0.04 s), standing for the timing error of each anchor. Temperature changes real crystal drift over time; this model keeps it constant.

On real hardware. nRF52840 DK. Log the ticks at two phone syncs several hours apart and compare the gap with the phone clock. Parts per million is the difference divided by the phone gap, times 1,000,000. Ten minutes is too short to see 20 ppm, which is only 12 ms, so wait hours.

Read the three lines. With one anchor, the error grows in a straight line forever. With a new offset at every sync, the error is capped at the drift between syncs, but records made just after a sync are still off by the full amount when the next one corrects them. With two anchors the phone can compute the clock’s rate, and the error nearly disappears.

Here is the two-anchor fix, with numbers. Anchor A says device tick 0 was wall time 0. Ten days later anchor B says device tick 864,017.28 s was wall time 864,000 s. The rate is 864,000 / 864,017.28, which is 0.99998. A record made at device tick 432,008.64 s gets wall time 432,000 s. The offset-only method would have said 432,008.64 s, which is 8.64 s too late.

A reboot resets the stopwatch

If the wearable resets, ticks start again at zero. A record with ticks 5,000 could belong to this boot or to the one last week. The anchor means nothing without knowing which.

The fix costs two bytes. Keep a boot number in flash. Increase it at every boot and save it. Put it in every record, next to the ticks. The phone then keeps one set of anchors for each boot number. The pair (boot number, sequence number) is also the key from Chapter 4, so a restart cannot make two records look the same.

One more trap: a 32-bit millisecond counter wraps after 232 ms, which is 49.7 days. Either store 64 bits, or treat a wrap as a new epoch and count it.

Put the anchor in the log

There is a robust trick. When the phone sets the time, the wearable writes an anchor into the log as an ordinary record: boot number, current ticks and the wall time the phone just sent. Now the log carries its own clock history. Even if the phone app is reinstalled, or the data is read on another computer, the old records can still be dated.

Bluetooth defines a Current Time characteristic for this job. Its value is an Exact Time 256 structure plus an adjust reason: year (16 bits), month, day, hours, minutes, seconds, day of week, and fractions of a second in units of 1/256 s, which is about 3.9 ms. Many products define their own simpler value, such as 64-bit Unix milliseconds. Store UTC on the wearable, and let the phone apply the time zone for display.

c/* Wearable: stamp each record with the boot number and uptime. No wall clock needed. */
static uint16_t boot_id;                       /* loaded from flash, +1, saved, at every boot */
void stamp(struct record *r) {
    r->boot_id = boot_id;
    r->ticks   = k_uptime_get_32();            /* ms since boot; wraps at 2^32 ms = 49.7 days */
}

/* Wearable: when the phone writes the time, log an anchor as a normal record. */
void on_time_write(int64_t unix_ms) {
    struct anchor a = { .boot_id = boot_id, .ticks = k_uptime_get_32(), .unix_ms = unix_ms };
    log_append_anchor(&a);
}
python# Phone: turn (boot_id, ticks) into wall time using the two nearest anchors of the same boot.
def wall_time(rec, anchors):
    a = anchors[rec.boot_id]                            # list of (ticks_ms, unix_ms), sorted by ticks
    (t1, w1), (t2, w2) = nearest_two(a, rec.ticks)
    rate = (w2 - w1) / (t2 - t1) if t2 != t1 else 1.0   # phone ms per device ms: 0.99998 for +20 ppm
    return w1 + (rec.ticks - t1) * rate
A crystal runs 20 ppm fast and the phone syncs once, then not for 10 days. How far off is a timestamp made on day 10, if the phone only used the first offset?

Chapter 7

Break It on Purpose

Run three designs through the same four disasters, and see which habit stops which failure

A bridge engineer does not trust a bridge because the drawings look fine. She loads it until something bends. Sync code deserves the same treatment. A sync that works on a desk, with the phone next to the board, proves almost nothing. The bugs live in the gaps: out of range, restarts, crashes, and full memory.

This chapter is the showcase. One run of 120 readings, one per second. Three designs listen to the same stream. You choose the disasters.

The three designs

Send and forget notifies each reading as it is made. If there is no link, it is gone. Resend the buffer keeps the 30 newest readings in RAM and sends all of them again whenever the link returns. Number and keep is this lesson’s design: every reading goes to a flash log with a sequence number and a boot number, the phone reports a cursor, and the phone saves before it acknowledges.

The four disasters

Away. The phone is out of range from second 30 to second 70. That is 40 readings with no link. Reboot. The wearable restarts at second 60, for example after a brown-out. Its RAM is wiped, its uptime counter restarts at zero, but its flash keeps the log. App dies. The phone app crashes, or the phone swaps it out of memory, from second 85 to 95. Tiny log. The flash log holds only 24 records instead of thousands.

There is also one switch that is a bug on purpose: phone acks before saving. It matters only when the app dies. The app has just received readings 82 to 84, sent the cursor, and then dies before writing them to its database.

Run the disasters

Each row is one design. Each thin cell is one reading, left to right over 120 seconds. Switch disasters on and off. Green arrived once with the right time. Red is lost. A red cap is a repeat. Yellow arrived with the wrong time. Purple outline is a gap the phone knows about.

A deterministic model of this lesson’s rules, not a radio test. Away is seconds 30 to 69, reboot at second 60, app down seconds 85 to 94. The resend design keeps 30 readings in RAM, and a reboot wipes them. The wrong-time column counts readings stamped with uptime that restarted at the reboot, with no boot number to repair it.

On real hardware. nRF52840 DK and a phone. Stage the four disasters: airplane mode for the gap, a battery disconnect for the reboot, force-stopping the app for the crash, and a one-sector log partition for the tiny log. After each run, check that no sequence is missing except known gaps and that no key repeats.

How to read the result

Start with the default: away, reboot and app death all on. Send and forget keeps 30 readings correct and loses 50. Resend the buffer is worse in a new way: it loses 30, and it also sends 20 readings twice, and 60 readings carry the wrong time. Number and keep delivers all 120 once, with the right time.

Now peel the disasters off one by one. With only Away, Send and forget loses 40. Resend the buffer loses 10, because its 30-reading buffer covers only part of the 40-second gap. Those 10 are the readings the buffer overwrote while you were still away. A bigger buffer helps, but only a log sized to the gap removes the failure.

With only Reboot, nothing is lost by either simple design, but 60 readings after the restart have the wrong time. Only the boot number lets the phone place them. This is the quiet failure: no gap in the chart, just a wrong date.

Turn on Tiny log with Away. Number and keep still loses data, 16 readings, but it reports them as a known gap, outlined in purple. A chart can show a clean break labelled “16 readings overwritten”. The other designs lose readings silently.

Last, switch on Phone acks before saving with the app death. Number and keep, the best design, now loses 3 readings for good. The wearable freed them on the cursor, and the phone never stored them. The protocol was right. One line of order in the phone code broke it. That is why Chapter 4 said save first.

What to test on real hardware

The same four disasters can be staged on a bench. Switch airplane mode on the phone for the gap. Disconnect the battery for the reboot. Force-stop the app for the crash. Use a log partition of one sector for the tiny log. After each run, compute the three invariants. The set of stored sequence numbers must have no holes except known gaps. No (boot number, sequence) key may appear twice. And every record must convert to a wall time within the drift error from Chapter 6.

With the wearable rebooting and nothing else going wrong, which design avoids the wrong timestamps?

Chapter 8

Field Guide: The Sync in One Page

Review the design, keep the numbers and the checklist, and find the sources and the next lessons

You can now rebuild a phone sync from first principles. The wearable keeps a numbered log in flash. The phone asks for what it lacks, saves it, and then says how far it got. The wearable frees only what is confirmed. And time is a count that the phone turns into a date, using anchors and a boot number.

The one-paragraph summary

BLE retries every packet while the link is up (SN and NESN bits), and drops everything queued when the supervision timer expires. Notifications carry no acknowledgement from the phone app, so reliability across a disconnect is the application’s job. Store each reading as a fixed-size record with a sequence number, a boot number and uptime ticks, in an append-only flash log whose entries carry a checksum. The phone reads the status, requests a range, saves what arrives keyed by (boot number, sequence), and writes a cumulative cursor with response. The wearable frees sectors up to the cursor. The phone converts ticks to wall time with the nearest two anchors of the same boot. Test with disasters, not with a desk.

The numbers that matter

WhatNumberWhere it comes from
Connection interval7.5 ms to 4.0 s, multiples of 1.25 msCore Spec 5.4, Link Layer
Supervision timeout100 ms to 32 s, multiples of 10 ms; larger than 2 × (1 + latency) × intervalCore Spec 5.4, Link Layer
Peripheral latency, largest499 (0x01F3)Zephyr hci_types.h, citing Core Spec 5.4 Vol 4 Part E
Link-layer acknowledgement1-bit SN and NESN; resend while NESN equals your SNCore Spec 5.4, Link Layer 4.5.9
Default LE ATT_MTU23 bytesCore Spec 5.4 Vol 3 Part G, Table 5.1
Largest notification valueATT_MTU − 3; 20 bytes at MTU 23; 244 at MTU 247Zephyr att.h, ATT spec
Indications in flightone, until the confirmation arrivesCore Spec 5.4, ATT 3.3.2
nRF52840 flash32-bit word writes, 2 writes per word, 41 µs per word, 85 ms page erase, 10,000 erase cyclesnRF52840 Product Specification, NVMC
Zephyr FCB entrylength + data + checksum; bad checksums skippedZephyr FCB documentation
A 24-byte entry log of 512 KB6.07 h at one per second; 128 sectors; about 6.9 years of wearArithmetic, Chapters 2 and 3
32-bit sequence number136 years at 1 Hz; 2.7 years at 50 Hz; 49.7 days at 1 kHzArithmetic, Chapter 4
Drain 21,600 records648 s (MTU 23, 1 per event, 30 ms); 10.8 s (MTU 247, 4 per event); 2.7 s at 7.5 msArithmetic, Chapter 5
Crystal drift20 ppm is 1.728 s per day; 500 ppm is 43.2 s per dayArithmetic, Chapter 6
32-bit millisecond uptimewraps after 49.7 daysArithmetic, Chapter 6
Current Time valueyear (16 bits), month, day, hours, minutes, seconds, weekday, fraction in 1/256 s, adjust reasonNordic CTS client header (nRF Connect SDK)

The checklist

  1. Write the policy first. How long must the device survive away, what does it drop when full, and how does the phone learn what was dropped?
  2. Size the log from bytes per second. Include the per-entry overhead and the sectors you reserve.
  3. Number every record with a counter that is read back from flash at boot, never kept only in RAM.
  4. Write data, then the checksum. Skip bad entries when reading. Let the number of the torn entry be reused.
  5. Free only confirmed sectors, and erase when the radio is idle.
  6. Make the receiver idempotent. Key every stored record by (boot number, sequence).
  7. Acknowledge with one cumulative cursor, written with response, after the phone has saved.
  8. Show gaps honestly. Compare the oldest sequence with the cursor and record known gaps.
  9. Go fast only while draining. Pack records into the MTU, then relax the connection interval.
  10. Back off with jitter when a sync fails, and never loop on a full queue.
  11. Stamp with uptime and boot number, log an anchor on every time write, and convert at the phone with two anchors.
  12. Test with disasters: away, reboot, app death, full log, early acknowledgement.

The wire format in one place

c/* One GATT service, four values. Little-endian, like the CPU. */
struct __packed sync_status {   /* READ    : the phone reads this first                        */
    uint16_t boot_id;          /* which power-up the newest record belongs to           */
    uint32_t oldest_seq;       /* first record still in flash                           */
    uint32_t newest_seq;       /* last record written                                   */
    uint32_t dropped;          /* records the ring overwrote before the phone saved them */
};
struct __packed sync_control {  /* WRITE   : "send me [from_seq, from_seq + count)"          */
    uint32_t from_seq;
    uint16_t count;
};
/* NOTIFY  : data, whole records back to back: floor((MTU - 3) / 16) per notification */
/* WRITE WITH RESPONSE : ack, one uint32_t cursor = "I saved everything up to here"   */

/* The three rules that make it safe:
   1. Wearable frees nothing above the last cursor it received.
   2. Phone writes the cursor only after its database commit.
   3. Phone keys records by (boot_id, seq), so a repeat changes nothing.            */

Where this sits

This lesson turns the radio from BLE from radio to GATT and the flash from flash filesystems and power fail into a product behaviour. Next to it sit the coin-cell year (what the fast sync costs in energy), pairing, bonding and privacy (who may read the log) and radio coexistence.

The clock half connects to what time is it on a chip, and to sensor and actuator integration for the same problem on a robot. When the stream is a biosignal that must line up exactly, see streaming it reliably. For updating the firmware itself over the same link, see bootloaders and OTA.

Keep going

Sources

Every number in the table was read from one of these pages, or derived from them in the chapter shown. The sync protocol itself (status, control, data, acknowledge) is this lesson’s own design: no standard defines it, and many products do something similar. Treat it as a pattern to adapt, not a specification. The FCB documentation does not give the sizes of its length and checksum fields, so the 8-byte overhead is a budgeting choice. Check the page size and endurance for your own part.

The takeaway. A phone sync is not a transfer, it is a promise kept across disconnects: keep it in flash, number it, let the phone say how far it got, save before you acknowledge, and date it later.

Now press Teach and explain, from memory, what happens to one reading made while the phone is out of range: where it lives, how the phone finds it, and how it gets its date. Then go back to the walk at the top, try each design at 12 s and at 36 s, and say which habit from this lesson fixes each failure you see.

Phone Sync That Survives Reality
Back to Gleams