Say you're building a messenger for crews who work out in the field. A dispatcher types a message into a web app, and it shows up on a crew member’s device a few minutes later.

If your solution only needs cellular connectivity, Blues makes this process straightforward. With Notecard Cellular, you can send commands to a device by adding a message to a .qi Notefile in Notehub. From there, Notehub handles delivering the message to your device based on your configuration.
Over satellite this process can take more work, especially if you need confirmation that a message was delivered successfully.
In this post, you'll learn why Notehub can't push data to a device over satellite, and how Notecard checks for inbound data instead. We’ll then cover when to send commands as environment variables versus Notes, and walk through a pattern for sending commands and confirming their delivery. Finally, I'll share the results of testing this approach with a Notecard for Skylo.
New to Blues?
Learn what we do in this 3-minute video that walks you through how we simplify wireless connectivity.
Learn what we do in this 3-minute video that walks you through how we simplify wireless connectivity.
Satellite Can't Push
Over cellular, Notehub can reach a Notecard that's connected. Over satellite (much like LoRaWAN), Notehub can only send data to Notecard as the reply to a packet in which Notecard asks for it. Notecard pulls down inbound data when:
- Your host sends a
hub.syncrequest with"in":true. - The
inboundinterval set withhub.set(or the_sync_inbound_mins_ntnenvironment variable, which takes priority while Notecard is on satellite) comes due.
The reply contains whatever was queued for the device when Notehub received the request. If more than one Note is waiting, Notecard fetches the rest automatically, one packet at a time.
A couple of other details about inbound syncs:
-
An outbound sync doesn’t sync inbound data on satellite. Over cellular and WiFi, a
hub.syncrequest with no arguments sends outbound Notes and picks up inbound data in the same session. Over satellite it only sends. The same goes for a Note added with"sync":true, and for syncs on theoutboundschedule. -
An inbound sync only picks up what was queued before it. After an inbound sync, Notecard keeps the satellite modem connected (180 seconds by default) so the reply has time to arrive. Anything queued after Notehub sends its reply waits for the next check, even if the modem is still connected.
-
Each inbound sync counts toward your satellite data usage just like any other sync. On Skylo, packets have a minimum billable size of 50 bytes, meaning even a check that sends less than 50 bytes is billed as 50 bytes. See How is satellite data billed? for more details.
Commands or Settings?
Notehub has two ways to get data down to a device over satellite: environment variables and
Notes in an inbound (.qi) Notefile. Both arrive through the same checks, but
they're good at different things.
Environment variables are great for settings, where only the latest value matters: a reporting interval, a threshold, a display brightness. If you change a variable twice between checks, the device only ever sees the second value, and that's exactly what you want.
Notes in a .qi Notefile are for commands and messages, where each Note matters. If two Notes are queued between inbound checks, both arrive.
A good rule of thumb: if you're defining how a device should be configured, use an environment variable. If you're telling a device to do (or display) something, use a .qi Note. The messenger example we introduced at the start of this blog post displays a message, so we’ll be using .qi Notes in the implementation.
The Pattern
With that background out of the way, let's walk through how our messenger gets a message from the dispatcher's web app to a device in the field, and how the dispatcher finds out that it arrived. Here's the whole flow, and then each step in more detail:
- Define compact templates for messages (
msg.qi) and confirmations (ack.qo), and sync them over cellular or WiFi first. - The cloud checks the message length, then queues it with an ID.
- The device checks for messages, either on Notecard's inbound schedule or when the host asks.
- The host reads
msg.qifrom Notecard. - The host adds an
ack.qoNote with the same ID and syncs it. - The cloud marks the message delivered, and resends it if no confirmation ever comes.
- If an ID arrives twice, the device confirms it again but doesn't show it twice.
Which Commands Need a Confirmation?
Steps 5 and 6 have the device confirm each message, and the cloud tracks those
confirmations. Not every command needs that, and to decide whether yours do, it
helps to know what Notehub already handles for you. Over Skylo, Notehub keeps each .qi Note until Skylo reports that it was
delivered. If Skylo reports a failure, or doesn't report back within 10
minutes, Notehub sends the Note again on the device's next check. You don't
need to write retry logic for ordinary satellite hiccups, and a message you
queue gets through as long as the device keeps checking.
What Notehub can't promise is when. A message that fails to arrive isn't sent again in the same session. It waits for the device's next check, which could be hours away if the device only checks a few times a day. So you can't count on a message arriving on any particular check.
That's what a confirmation is for. It tells your cloud application that a specific message reached the device, and when. Each confirmation uses satellite data, even though it goes out on the connection that's already open.
You can usually skip the confirmation when:
- The device's regular reports already show the result. If you tell a pump to turn on, the next reading that shows it running is your confirmation.
- A missed command does no harm, or gets sent again anyway, like a request to refresh a display.
Ask for a confirmation when a command has to happen once and someone needs to know that it did, like a message a person has to read or an alarm that has to be silenced. Our messenger's messages are in this group, because the dispatcher wants to see "delivered."
Define the Templates
Notes only travel over satellite if they have a compact template, and Notehub
has to learn each template over cellular or WiFi before the device can use it
(see
Always Sync with Notehub First).
For our example, the host defines the following two templates at startup with
note.template:
{
"req": "note.template",
"file": "msg.qi",
"format": "compact",
"port": 40,
"body": {"id": 24, "sent": 24, "text": "x"}
}{
"req": "note.template",
"file": "ack.qo",
"format": "compact",
"port": 41,
"body": {"id": 24, "status": 21, "_time": 14}
}The numbers are field types: 24 is a 32-bit unsigned integer, 21 an 8-bit
unsigned integer, and 14 a 32-bit integer (here, the time Notecard created
the confirmation). A message carries its ID, the time the cloud sent it, and
its text. A confirmation carries the message's ID and a status (more on those
values in a minute).
Keep Every Message Inside One Packet
A Skylo packet holds 256 bytes, and a satellite Note has to fit in one. In our tests, a 200-character message went down as 246 bytes, with the ID, timestamp, and framing taking the other 46. That leaves room for about 210 bytes of text with this template. We use 200 as a max length below to stay well within the limit.
Queue a Message
Your cloud application queues a message with the Notehub API's Add QI Note endpoint. Here it is in Python:
import time
import requests
API = "https://api.notefile.net"
MAX_TEXT_BYTES = 200 # fits in one Skylo packet with our template
def queue_message(project, device, token, msg_id, text):
if len(text.encode("utf-8")) > MAX_TEXT_BYTES:
raise ValueError("message too long to send over satellite")
requests.post(
f"{API}/v1/projects/{project}/devices/{device}/notes/msg.qi",
headers={"Authorization": f"Bearer {token}"},
json={"body": {"id": msg_id, "sent": int(time.time()), "text": text}},
).raise_for_status()You’ll likely want to store each message in your own database with its ID
and a pending status. You'll need that record later to match confirmations
and to decide whether to resend.
Check for Messages
There are two ways to have your device check Notehub for any inbound data, and you can use either one or both.
Let Notecard check on a schedule. Set an inbound interval with
hub.set, and Notecard checks on its own when the interval comes due. For
example, with the configuration below your Notecard checks for inbound data
every 240 minutes, or every 4 hours.
{"req": "hub.set", "mode": "periodic", "inbound": 240}With this approach, your host MCU never has to start a check. Notecard performs
the sync automatically, and your host only needs to read msg.qi every few seconds
and confirm whatever shows up.
To change the interval on
deployed devices, you can set the _sync_inbound_mins_ntn environment variable,
which takes priority while Notecard is on satellite.
Have the host check. This is useful when the host knows a reply is coming, or is reacting to some activity on the device itself.
{"req": "hub.sync", "in": true}Either way, the interval you choose comes down to how late a message can be. A message queued just after a check waits a full interval for the next one.
Our test firmware below has a "check for messages now" command, and tying a check to a button like that is handy for testing. In a real product it gets expensive really fast. Each check over satellite is billed at least 50 bytes even when no message is waiting, and Notecard for Skylo includes 10 KB of satellite data:
| Check every | Checks per day | Billed per day | 10 KB lasts |
|---|---|---|---|
| 15 minutes | 96 | 4.8 KB | about 2 days |
| 1 hour | 24 | 1.2 KB | about 8 days |
| 6 hours | 4 | 200 bytes | about 50 days |
| 24 hours | 1 | 50 bytes | about 200 days |
Read and Confirm Each Message
The host reads messages with
note.get and
"delete":true until Notecard reports {note-noexist}, confirms each one in
ack.qo, and then syncs once. Here's that loop in C with
note-c:
#define STATUS_DELIVERED 1 // first time this ID arrived
#define STATUS_DUPLICATE 2 // this ID arrived again; confirm it again
#define SEEN_SLOTS 32
static uint32_t seenIds[SEEN_SLOTS];
static int seenCount = 0;
static int seenNext = 0;
static bool seenBefore(uint32_t id) {
for (int i = 0; i < seenCount; i++) {
if (seenIds[i] == id) {
return true;
}
}
return false;
}
static void rememberId(uint32_t id) {
seenIds[seenNext] = id;
seenNext = (seenNext + 1) % SEEN_SLOTS;
if (seenCount < SEEN_SLOTS) {
seenCount++;
}
}
static void confirm(uint32_t id, int status) {
J *req = NoteNewRequest("note.add");
JAddStringToObject(req, "file", "ack.qo");
J *body = JAddObjectToObject(req, "body");
JAddNumberToObject(body, "id", id);
JAddNumberToObject(body, "status", status);
NoteRequest(req);
}
// Call every few seconds. Reading msg.qi is local, so it costs no data.
void readMessages(void) {
int confirmed = 0;
while (true) {
J *req = NoteNewRequest("note.get");
JAddStringToObject(req, "file", "msg.qi");
JAddBoolToObject(req, "delete", true);
J *rsp = NoteRequestResponse(req);
if (rsp == NULL) {
break;
}
if (NoteResponseError(rsp)) { // {note-noexist}: nothing waiting
NoteDeleteResponse(rsp);
break;
}
J *body = JGetObject(rsp, "body");
uint32_t id = (uint32_t) JGetNumber(body, "id");
if (seenBefore(id)) {
confirm(id, STATUS_DUPLICATE);
} else {
rememberId(id);
showMessage(JGetString(body, "text"));
confirm(id, STATUS_DELIVERED);
}
NoteDeleteResponse(rsp);
confirmed++;
}
if (confirmed > 0) {
NoteRequest(NoteNewRequest("hub.sync"));
}
}A few details are worth calling out.
Sync the confirmations right away. After a check, Notecard keeps the
satellite modem connected for 180 seconds after its last packet, so a message
arrives while the modem is still connected. Keeping the modem connected
doesn't send anything on its own, though. A new ack.qo Note waits in
Notecard until something starts an outbound sync, which is why the loop above
ends with a hub.sync request. (Adding the last confirmation with
"sync":true works too.) Sync while the modem is still connected, and the
confirmation goes out on the same connection a few seconds later. Wait until
the modem has powered off, and the confirmation needs a whole new connection.
Confirm duplicates too. When Notecard sends a packet over satellite, it
never learns whether that packet reached Notehub, and a packet lost along the
way isn't sent again (see
Plan for Data Loss).
That includes the packet carrying a confirmation. To your cloud application, a
lost confirmation looks the same as a
message that never arrived, so it eventually sends the message again. If the
device ignores the copy, the cloud still hears nothing, and after a few tries
it marks a message the device already showed as failed. So the device confirms
the copy (with status 2, meaning "already had this one") without showing it
again. The same goes for the occasional duplicate from Notehub's own retries.
Sort by ID, not arrival order. A resent message can arrive after newer ones.
Track Delivery in the Cloud
Notehub resends undelivered messages for you, as covered above. Your cloud application still needs to track confirmations, though, for a few reasons:
- A confirmation tells you that the device got the message, and when. That's what the dispatcher's "delivered" label is built on.
- Confirmations can get lost too. Notecard doesn't find out when a packet it sends over satellite is lost, so it doesn't resend it. A lost confirmation looks exactly like a message that never arrived.
- A message can arrive twice. Notehub's retries mean delivery is at-least-once, which is another reason the device confirms duplicates and ignores their contents.
To receive confirmations, set up a
route that sends
ack.qo events to your application, and mark each message delivered when its
ID comes back with status 1 or 2.
Then, as a backstop, look for messages that have gone unconfirmed for a long time. Before resending one, ask Notehub whether it's still holding the Note with the API's Get Notefile Changes endpoint. If it is, the device just hasn't checked yet, and a resend would only create a duplicate:
RESEND_AFTER = 6 * 60 * 60 # longer than the device's check interval
MAX_ATTEMPTS = 3
def still_queued(project, device, token):
rsp = requests.get(
f"{API}/v1/projects/{project}/devices/{device}/notes/msg.qi",
headers={"Authorization": f"Bearer {token}"},
)
rsp.raise_for_status()
notes = (rsp.json().get("notes") or {}).values()
return {note["body"]["id"] for note in notes if "id" in note.get("body", {})}
def resend_unconfirmed(project, device, token, messages):
queued = still_queued(project, device, token)
for msg in messages:
if msg.status != "pending" or time.time() - msg.last_sent < RESEND_AFTER:
continue
if msg.id in queued:
continue # waiting for the device's next check
if msg.attempts >= MAX_ATTEMPTS:
msg.status = "failed" # tell the sender
continue
queue_message(project, device, token, msg.id, msg.text)
msg.attempts += 1
msg.last_sent = time.time()Make the resend timeout comfortably longer than the device's check interval,
and give up after a few attempts so a device that's switched off doesn't
collect a pile of copies. A message marked failed is something to show the
sender, not something to keep retrying silently.
My Test Run
To test things out, I ran this pattern on a Notecard for Skylo (NOTE-NBGLWX) with firmware 11.4.1 on a Notecarrier CX, with the default 180-second modem window. You can view the full host firmware I ran below.
To try it out, you’ll need to queue a msg.qi Note in Notehub with an id. If everything works correctly, you should see an ack.qo Note come back from the device on its next inbound interval. For example, below I sent a msg.qi Note to Notehub at 12:39 PM, and received confirmation on my device’s next inbound interval at around 1:18 PM.

Summary
Getting a command to a satellite device takes a little more thought than over cellular, because the device has to ask. To recap:
- Notehub can't push over satellite. Messages arrive on the next check, either
from
hub.syncwith"in":trueor Notecard's inbound schedule. Ahub.syncwithout"in":trueonly sends. - Every check costs at least 50 bytes on Skylo, so pick the check interval by how late a message can be, and don't put a "check now" button in a product.
- Use environment variables for settings and
.qiNotes with IDs. - Check message length in the cloud to ensure they fit within a packet.
- Have the device confirm every message right away, including duplicates, and have your cloud application resend only what's no longer queued and still unconfirmed.
For more on designing for satellite, see the Satellite Best Practices guide. And if you build something with it, let us know!
Happy hacking! 💙
The Full Host Firmware
Here's the complete host firmware we ran for the measurements above. It's an Arduino sketch that uses note-arduino, and we ran it on a Notecarrier CX, which logs through its ST-LINK's virtual COM port.
Keep in mind that this is test firmware. Along with the pattern from this post, it has serial commands for starting checks and switching transports, counters, and a log line whenever the satellite modem connects or disconnects, so the timings could be read straight off the serial log. Don't ship the "check now" command (see the warning in Check for Messages).
To try it, set PRODUCT_UID in config.h, then build and flash the sketch.
For the Notecarrier CX:
arduino-cli compile --fqbn STMicroelectronics:stm32:Blues:pnum=CYGNET,usb=none .Open a serial monitor at 115200 baud and type h to list the commands. Type
l once to sync the templates over cellular before you test over satellite.
config.h
// Settings for the NTN messenger test firmware. Change these, then rebuild.
#pragma once
// ---- Notehub ---------------------------------------------------------------
// Notehub ProductUID. Leave empty to keep whatever the Notecard already has.
#define PRODUCT_UID "com.your-company.your-name:your_product"
// When 1, boot sends hub.set with PRODUCT_UID (if set), periodic mode and the
// intervals below. When 0, the Notecard's hub settings are left alone.
#define CONFIGURE_HUB 1
// The host triggers every sync in this test, so keep the Notecard's own
// intervals long. Otherwise the Notecard adds its own inbound checks and the
// timing results get muddied. Note: _sync_inbound_mins_ntn, if set in Notehub,
// overrides the inbound interval over NTN. Boot logs its value.
#define HUB_OUTBOUND_MINS 1440
#define HUB_INBOUND_MINS 1440
// ---- Templates -------------------------------------------------------------
// Compact-template ports (1-100). Each must be unique within the product.
// Changing either one means syncing over cellular again before using NTN.
#define MSG_PORT 40 // msg.qi: messages from the cloud
#define ACK_PORT 41 // ack.qo: confirmations from the device
// ---- Checking for messages ---------------------------------------------------
// Scheduled check (hub.sync in:true) every N seconds. 0 = manual checks only.
// Every check is billed (at least 50 bytes on Skylo), so on a real product this
// should be long. 15 min = 96 checks/day = ~4.8 KB/day before any messages.
#define CHECK_INTERVAL_SECS 0
// Minimum seconds between checks of any kind (button, serial, schedule).
// Guards against a bouncing or held button running up the bill.
#define MIN_CHECK_GAP_SECS 30
// ---- Confirmations ---------------------------------------------------------
// true: after adding confirmations, send them right away with hub.sync
// (one packet for all the confirmations from that read).
// false: leave them queued in ack.qo until something else syncs.
#define ACK_SYNC_NOW true
// ---- Local polling (I2C only, costs nothing over the air) ----------------------
// How often to read msg.qi from the Notecard.
#define DRAIN_INTERVAL_MS 5000
// How often to read ntn.status to log when the satellite modem connects and
// disconnects. 0 = off.
#define MODEM_WATCH_MS 2000
// ---- Hardware --------------------------------------------------------------
// 1 = a button triggers a check. Off by default: the Notecarrier CX has no
// user button (only RST and BOOT), and a floating input could fire billed
// checks. On a Swan, USER_BTN works; its idle level is read at boot.
#define USE_BUTTON 0
#ifdef USER_BTN
#define BUTTON_PIN USER_BTN
#else
#define BUTTON_PIN 2
#endif
// 1 = log to the ST-LINK virtual COM port (LPUART1 on the debug jack) when the
// board has one, as on the Notecarrier CX. 0 = log to USB Serial.
#define USE_VCP_SERIAL 1
// 1 = print every Notecard request and response to Serial at boot ('d' toggles it).
#define NOTECARD_DEBUG 0
// How many recent message IDs to remember for ignoring duplicates (RAM only,
// lost on reset).
#define DEDUPE_SLOTS 32
// How many unread messages to track for read confirmations.
#define UNREAD_SLOTS 16ntn-messenger.ino
// NTN messenger test firmware
//
// The cloud queues messages in msg.qi. Over satellite they only reach the
// Notecard as the reply to a check (hub.sync in:true), so this host triggers
// checks on a button press, a serial command or an optional schedule. It reads
// msg.qi locally, prints each message, and confirms it in ack.qo with the
// message ID, so the cloud can resend anything it never hears back about.
//
// Settings are in config.h. Serial commands: type 'h' for help.
#include <Notecard.h>
#include <stdarg.h>
#include "config.h"
// Log output: the ST-LINK virtual COM port if the board has one, else USB Serial
#if USE_VCP_SERIAL && defined(PIN_VCP_RX) && defined(PIN_VCP_TX)
Uart vcpSerial(PIN_VCP_RX, PIN_VCP_TX);
#define LOG vcpSerial
#define LOG_IS_VCP 1
#else
#define LOG Serial
#define LOG_IS_VCP 0
#endif
// ack.qo status values
#define ACK_PING 0 // plain outbound sync, not a confirmation ('u' command)
#define ACK_DELIVERED 1 // first time this ID arrived
#define ACK_DUPLICATE 2 // ID arrived again (cloud resent it); confirm again
#define ACK_READ 3 // a person read it ('r' command)
#define MAX_TEXT 256
Notecard notecard;
// Counters printed by the 's' command
struct {
uint32_t checks;
uint32_t checksSkipped;
uint32_t received;
uint32_t duplicates;
uint32_t outOfOrder;
uint32_t acksQueued;
uint32_t ackErrors;
uint32_t syncs;
} stats;
// Recently seen IDs, for ignoring resent messages
static uint32_t seenIds[DEDUPE_SLOTS];
static uint8_t seenCount = 0;
static uint8_t seenNext = 0;
// Messages shown but not yet marked read
static uint32_t unreadIds[UNREAD_SLOTS];
static uint8_t unreadCount = 0;
static bool haveLastId = false;
static uint32_t lastId = 0;
static bool haveChecked = false;
static uint32_t lastCheckMs = 0;
static uint32_t nextScheduledCheckMs = 0;
static uint32_t lastDrainMs = 0;
static bool modemWatchEnabled = (MODEM_WATCH_MS > 0);
static int modemConnected = -1; // -1 unknown, 0 no, 1 yes
static uint32_t modemChangedMs = 0;
static uint32_t lastModemWatchMs = 0;
static bool debugOn = (NOTECARD_DEBUG != 0);
static int buttonIdle = HIGH;
static int buttonLast = HIGH;
static uint32_t buttonChangedMs = 0;
static bool buttonHandled = true;
// ---------------------------------------------------------------------------
// Logging. Every line starts with seconds since boot, so timings can be read
// straight off the serial log.
static void logf(const char *fmt, ...)
{
char buf[384];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
uint32_t ms = millis();
char stamp[24];
snprintf(stamp, sizeof(stamp), "[%6lu.%01lu] ", (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100));
LOG.print(stamp);
LOG.println(buf);
}
// Format a millisecond duration as "12.3s"
static const char *secs(uint32_t ms, char *buf, size_t len)
{
snprintf(buf, len, "%lu.%01lus", (unsigned long)(ms / 1000), (unsigned long)((ms % 1000) / 100));
return buf;
}
static void logJson(const char *label, J *json)
{
if (json == NULL) {
logf("%s: (no response)", label);
return;
}
char *s = JPrintUnformatted(json);
if (s != NULL) {
logf("%s: %s", label, s);
JFree(s);
}
}
// Send a request, log the response, and free it. Returns false on error.
static bool requestLogged(const char *label, J *req)
{
J *rsp = notecard.requestAndResponse(req);
logJson(label, rsp);
bool ok = (rsp != NULL) && !notecard.responseError(rsp);
notecard.deleteResponse(rsp);
return ok;
}
// Notecard's clock (epoch seconds), or 0 if it doesn't have the time yet
static uint32_t notecardEpoch(void)
{
uint32_t t = 0;
J *rsp = notecard.requestAndResponse(notecard.newRequest("card.time"));
if (rsp != NULL && !notecard.responseError(rsp)) {
t = (uint32_t) JGetNumber(rsp, "time");
}
notecard.deleteResponse(rsp);
return t;
}
// ---------------------------------------------------------------------------
// Setup
static void logEnv(const char *name)
{
J *req = notecard.newRequest("env.get");
JAddStringToObject(req, "name", name);
J *rsp = notecard.requestAndResponse(req);
const char *text = (rsp != NULL) ? JGetString(rsp, "text") : "";
logf("env %s = %s", name, (text != NULL && text[0] != '\0') ? text : "(not set)");
notecard.deleteResponse(rsp);
}
static void defineTemplates(void)
{
// Messages from the cloud: an ID, the cloud's send time (epoch seconds,
// 0 if unknown) and the text. The string is variable length; its value
// here just has to be non-empty.
J *req = notecard.newRequest("note.template");
JAddStringToObject(req, "file", "msg.qi");
JAddStringToObject(req, "format", "compact");
JAddNumberToObject(req, "port", MSG_PORT);
J *body = JAddObjectToObject(req, "body");
JAddNumberToObject(body, "id", 24); // uint32
JAddNumberToObject(body, "sent", 24); // uint32
JAddStringToObject(body, "text", "x"); // string
requestLogged("template msg.qi", req);
// Confirmations from the device: the message ID, a status, and the time
// the Notecard created the Note.
req = notecard.newRequest("note.template");
JAddStringToObject(req, "file", "ack.qo");
JAddStringToObject(req, "format", "compact");
JAddNumberToObject(req, "port", ACK_PORT);
body = JAddObjectToObject(req, "body");
JAddNumberToObject(body, "id", 24); // uint32
JAddNumberToObject(body, "status", 21); // uint8
JAddNumberToObject(body, "_time", 14);
requestLogged("template ack.qo", req);
}
static void configureNotecard(void)
{
requestLogged("card.version", notecard.newRequest("card.version"));
if (CONFIGURE_HUB) {
J *req = notecard.newRequest("hub.set");
if (PRODUCT_UID[0] != '\0') {
JAddStringToObject(req, "product", PRODUCT_UID);
}
JAddStringToObject(req, "mode", "periodic");
JAddNumberToObject(req, "outbound", HUB_OUTBOUND_MINS);
JAddNumberToObject(req, "inbound", HUB_INBOUND_MINS);
requestLogged("hub.set", req);
}
defineTemplates();
requestLogged("card.transport", notecard.newRequest("card.transport"));
logEnv("_ntn_modem_secs");
logEnv("_sync_inbound_mins_ntn");
}
// ---------------------------------------------------------------------------
// Checking for messages
static void checkNow(const char *reason)
{
uint32_t now = millis();
if (haveChecked && (now - lastCheckMs) < (uint32_t)MIN_CHECK_GAP_SECS * 1000) {
char b[16];
stats.checksSkipped++;
logf("CHECK skipped (%s): last check was %s ago, minimum gap is %ds",
reason, secs(now - lastCheckMs, b, sizeof(b)), MIN_CHECK_GAP_SECS);
return;
}
J *req = notecard.newRequest("hub.sync");
JAddBoolToObject(req, "in", true);
J *rsp = notecard.requestAndResponse(req);
if (rsp == NULL || notecard.responseError(rsp)) {
logJson("CHECK failed", rsp);
} else {
stats.checks++;
haveChecked = true;
lastCheckMs = now;
logf("CHECK #%lu sent (%s): hub.sync in:true", (unsigned long)stats.checks, reason);
}
notecard.deleteResponse(rsp);
}
static void syncOut(const char *reason)
{
J *req = notecard.newRequest("hub.sync");
J *rsp = notecard.requestAndResponse(req);
if (rsp == NULL || notecard.responseError(rsp)) {
logJson("SYNC failed", rsp);
} else {
stats.syncs++;
logf("SYNC sent (%s): hub.sync (outbound only)", reason);
}
notecard.deleteResponse(rsp);
}
// ---------------------------------------------------------------------------
// Messages and confirmations
static bool seenBefore(uint32_t id)
{
for (uint8_t i = 0; i < seenCount; i++) {
if (seenIds[i] == id) {
return true;
}
}
return false;
}
static void rememberId(uint32_t id)
{
seenIds[seenNext] = id;
seenNext = (seenNext + 1) % DEDUPE_SLOTS;
if (seenCount < DEDUPE_SLOTS) {
seenCount++;
}
}
static bool queueAck(uint32_t id, uint8_t status)
{
J *req = notecard.newRequest("note.add");
JAddStringToObject(req, "file", "ack.qo");
J *body = JAddObjectToObject(req, "body");
JAddNumberToObject(body, "id", id);
JAddNumberToObject(body, "status", status);
J *rsp = notecard.requestAndResponse(req);
bool ok = (rsp != NULL) && !notecard.responseError(rsp);
if (ok) {
stats.acksQueued++;
logf("ACK queued id=%lu status=%u", (unsigned long)id, status);
} else {
stats.ackErrors++;
logJson("ACK failed", rsp);
}
notecard.deleteResponse(rsp);
return ok;
}
static void handleMessage(uint32_t id, uint32_t sent, const char *text, uint32_t epoch)
{
uint32_t now = millis();
bool dup = seenBefore(id);
char sinceCheck[16] = "n/a";
if (haveChecked) {
secs(now - lastCheckMs, sinceCheck, sizeof(sinceCheck));
}
char latency[16] = "n/a";
if (sent != 0 && epoch != 0 && epoch >= sent) {
snprintf(latency, sizeof(latency), "%lus", (unsigned long)(epoch - sent));
}
if (dup) {
stats.duplicates++;
logf("RX DUPLICATE id=%lu since_check=%s latency=%s (not shown again)",
(unsigned long)id, sinceCheck, latency);
queueAck(id, ACK_DUPLICATE);
return;
}
stats.received++;
rememberId(id);
bool outOfOrder = haveLastId && id < lastId;
if (outOfOrder) {
stats.outOfOrder++;
}
if (!haveLastId || id > lastId) {
lastId = id;
haveLastId = true;
}
logf("RX id=%lu len=%u since_check=%s latency=%s%s",
(unsigned long)id, (unsigned)strlen(text), sinceCheck, latency,
outOfOrder ? " OUT-OF-ORDER" : "");
LOG.println();
LOG.print(" >> ");
LOG.println(text);
LOG.println();
if (unreadCount < UNREAD_SLOTS) {
unreadIds[unreadCount++] = id;
}
queueAck(id, ACK_DELIVERED);
}
// Read every message waiting in msg.qi. Local I2C only; costs nothing over the air.
static void drainMessages(void)
{
int acks = 0;
uint32_t epoch = 0;
bool haveEpoch = false;
for (int i = 0; i < 10; i++) {
J *req = notecard.newRequest("note.get");
JAddStringToObject(req, "file", "msg.qi");
JAddBoolToObject(req, "delete", true);
J *rsp = notecard.requestAndResponse(req);
if (rsp == NULL) {
logf("note.get msg.qi: no response");
break;
}
if (notecard.responseError(rsp)) {
const char *err = JGetString(rsp, "err");
// {note-noexist}: nothing waiting. A missing notefile just means
// nothing has ever arrived.
if (!NoteErrorContains(err, "{note-noexist}") && !NoteErrorContains(err, "{notefile-noexist}")) {
logJson("note.get msg.qi", rsp);
}
notecard.deleteResponse(rsp);
break;
}
if (!haveEpoch) {
epoch = notecardEpoch();
haveEpoch = true;
}
J *body = JGetObject(rsp, "body");
uint32_t id = (uint32_t) JGetNumber(body, "id");
uint32_t sent = (uint32_t) JGetNumber(body, "sent");
const char *text = JGetString(body, "text");
char textCopy[MAX_TEXT];
strlcpy(textCopy, (text != NULL) ? text : "", sizeof(textCopy));
notecard.deleteResponse(rsp);
handleMessage(id, sent, textCopy, epoch);
acks++;
}
if (acks > 0 && ACK_SYNC_NOW) {
syncOut("send confirmations");
}
}
static void markAllRead(void)
{
if (unreadCount == 0) {
logf("No unread messages");
return;
}
for (uint8_t i = 0; i < unreadCount; i++) {
queueAck(unreadIds[i], ACK_READ);
}
unreadCount = 0;
if (ACK_SYNC_NOW) {
syncOut("send read confirmations");
}
}
// A plain outbound sync with no inbound check, for testing whether it brings
// back queued messages (it doesn't).
static void sendPing(void)
{
if (queueAck(0, ACK_PING)) {
syncOut("ping");
}
}
// ---------------------------------------------------------------------------
// Modem watch: log when the satellite modem connects and disconnects
static void watchModem(void)
{
J *rsp = notecard.requestAndResponse(notecard.newRequest("ntn.status"));
if (rsp == NULL) {
return;
}
if (notecard.responseError(rsp)) {
logJson("ntn.status failed, modem watch off", rsp);
modemWatchEnabled = false;
notecard.deleteResponse(rsp);
return;
}
const char *status = JGetString(rsp, "status");
int connected = (status != NULL && strstr(status, "{ntn-connected}") != NULL) ? 1 : 0;
if (connected != modemConnected) {
uint32_t now = millis();
char b1[16], b2[16] = "n/a";
if (modemConnected >= 0) {
secs(now - modemChangedMs, b1, sizeof(b1));
} else {
strlcpy(b1, "n/a", sizeof(b1));
}
if (haveChecked) {
secs(now - lastCheckMs, b2, sizeof(b2));
}
logf("MODEM %s after %s (since_check=%s) status=%s",
connected ? "CONNECTED" : "DISCONNECTED", b1, b2, status != NULL ? status : "");
modemConnected = connected;
modemChangedMs = now;
}
notecard.deleteResponse(rsp);
}
// ---------------------------------------------------------------------------
// Status and serial commands
static void printStatus(void)
{
logf("STATS checks=%lu skipped=%lu received=%lu duplicates=%lu out_of_order=%lu acks=%lu ack_errors=%lu syncs=%lu unread=%u",
(unsigned long)stats.checks, (unsigned long)stats.checksSkipped,
(unsigned long)stats.received, (unsigned long)stats.duplicates,
(unsigned long)stats.outOfOrder, (unsigned long)stats.acksQueued,
(unsigned long)stats.ackErrors, (unsigned long)stats.syncs, unreadCount);
requestLogged("ntn.status", notecard.newRequest("ntn.status"));
requestLogged("card.transport", notecard.newRequest("card.transport"));
requestLogged("hub.sync.status", notecard.newRequest("hub.sync.status"));
logEnv("_ntn_modem_secs");
}
static void setTransport(const char *method)
{
J *req = notecard.newRequest("card.transport");
JAddStringToObject(req, "method", method);
requestLogged("card.transport", req);
}
static void printHelp(void)
{
LOG.println();
LOG.println("Commands:");
LOG.println(" c check for messages now (hub.sync in:true; billed)");
LOG.println(" r send read confirmations for all unread messages");
LOG.println(" u plain outbound sync with no inbound check (ack.qo status 0)");
LOG.println(" s status: counters, ntn.status, transport, sync status");
LOG.println(" l cellular with satellite fallback (cell-ntn), then sync; use to push templates");
LOG.println(" n satellite only (card.transport ntn) for testing");
LOG.println(" d toggle Notecard request/response debug output");
LOG.println(" h this help");
LOG.println();
}
static void handleSerial(void)
{
while (LOG.available() > 0) {
char c = (char) LOG.read();
switch (c) {
case 'c':
checkNow("serial");
break;
case 'r':
markAllRead();
break;
case 'u':
sendPing();
break;
case 's':
printStatus();
break;
case 'l':
setTransport("cell-ntn");
syncOut("push templates over cellular");
logf("Watch the sync with 's' until hub.sync.status shows it completed");
break;
case 'n':
setTransport("ntn");
break;
case 'd':
debugOn = !debugOn;
if (debugOn) {
notecard.setDebugOutputStream(LOG);
} else {
notecard.clearDebugOutputStream();
}
logf("Notecard debug %s", debugOn ? "on" : "off");
break;
case 'h':
case '?':
printHelp();
break;
default:
break;
}
}
}
static void handleButton(void)
{
int level = digitalRead(BUTTON_PIN);
uint32_t now = millis();
if (level != buttonLast) {
buttonLast = level;
buttonChangedMs = now;
buttonHandled = false;
}
// Act once per press, after 50 ms of a steady pressed level
if (!buttonHandled && level != buttonIdle && (now - buttonChangedMs) > 50) {
buttonHandled = true;
checkNow("button");
}
}
// ---------------------------------------------------------------------------
void setup()
{
LOG.begin(115200);
#if !LOG_IS_VCP
uint32_t start = millis();
while (!Serial && (millis() - start) < 5000) {
delay(10);
}
#endif
if (USE_BUTTON) {
pinMode(BUTTON_PIN, INPUT);
buttonIdle = digitalRead(BUTTON_PIN);
buttonLast = buttonIdle;
}
notecard.begin();
if (debugOn) {
notecard.setDebugOutputStream(LOG);
}
logf("NTN messenger test firmware");
configureNotecard();
if (CHECK_INTERVAL_SECS > 0) {
nextScheduledCheckMs = millis() + (uint32_t)CHECK_INTERVAL_SECS * 1000;
logf("Scheduled check every %ds", CHECK_INTERVAL_SECS);
} else {
logf("No scheduled checks; press the button or type 'c'");
}
printHelp();
}
void loop()
{
uint32_t now = millis();
handleSerial();
if (USE_BUTTON) {
handleButton();
}
if (CHECK_INTERVAL_SECS > 0 && (int32_t)(now - nextScheduledCheckMs) >= 0) {
nextScheduledCheckMs = now + (uint32_t)CHECK_INTERVAL_SECS * 1000;
checkNow("schedule");
}
if (now - lastDrainMs >= DRAIN_INTERVAL_MS) {
lastDrainMs = now;
drainMessages();
}
if (modemWatchEnabled && now - lastModemWatchMs >= MODEM_WATCH_MS) {
lastModemWatchMs = now;
watchModem();
}
delay(10);
}Frequently Asked Questions
Can Notehub push data to a satellite IoT device?
No. Over satellite, inbound data such as Notes in .qi Notefiles and
environment variable changes only reach Notecard as the reply to a packet in
which Notecard asks for it. That check happens when the host sends hub.sync
with "in":true, or when the inbound interval comes due. A hub.sync without
"in":true only sends outbound data over satellite, and anything queued after a
check waits for the next one.
How quickly does a command reach a satellite IoT device?
On the device's next check for inbound data, so choose the check interval by how late a command can be. In our tests on Notecard for Skylo, a message arrived 1.5 to 3 minutes after a check that had to connect to the satellite first, and about 15 seconds after a check made while the modem was still connected. Checking often has a cost: each check is billed at least 50 bytes on Skylo even when nothing is waiting, so checking every 15 minutes uses Notecard for Skylo's included 10 KB in about two days.
How long can a command sent over satellite be?
It has to fit in one Skylo packet of 256 bytes, along with the template's other fields and some overhead. With a message ID, a timestamp, and a text field, 200 characters of text fit and 250 didn't.
Should I use environment variables or .qi Notes to send commands over satellite?
Use environment variables for settings, where only the latest value matters.
Use Notes in a .qi Notefile for commands that should happen once per request,
can pile up, or need to be confirmed individually. An environment variable that
changes twice between checks only delivers its last value.
Do I need to confirm every command sent to a satellite IoT device?
No. Over Skylo, Notehub keeps each .qi Note until Skylo reports it delivered,
and sends it again on the device's next check if it wasn't. A confirmation is
how your application learns that a specific command reached the device, and
when, so use one when someone needs to know. Give the command an ID, and have
the host add a Note with the same ID to an outbound .qo Notefile as soon as it
reads the command, confirming a repeated ID again without acting on it twice.
Skip confirmations when the device's regular reports already show the result,
because each one uses satellite data.

