SMS brána pro desku Gateway Pro
Dokumentace firmwaru verze 1.0.0 pro správce brány a vývojáře integrací (REST API, webhook).
SMS gateway for the Gateway Pro board
Documentation of firmware version 1.0.0 for the administrator of the gateway and for integration developers (REST API, webhook).
Rychlý start
- Zapojení. Vložte SIM se službou SMS, připojte ethernetový kabel a napájení (PoE nebo USB).
- Adresa brány. Brána dostane adresu z DHCP – najdete ji v seznamu klientů routeru. Nové zařízení bez linku Ethernetu spustí asi po 10 s otevřenou WiFi
SMS-GW-XXXXXX; připojte se k ní a otevřetehttp://10.217.88.1/. - Heslo. Otevřete
http://<adresa brány>/a přihlaste se prázdným heslem. Na prázdné desce nejdřív naformátujte úložiště (formulář nahoře), pak nastavte heslo správce (8–64 znaků). - Kontrola. Zhruba minutu po startu (modem se zapne asi po 20 s a pak se registruje) ověřte na stránce Status, že modem je připravený, SIM je v pořádku, je registrovaný v síti a má signál.
- API klíč. Na stránce API keys vytvořte klíč (oprávnění
sendareadjsou předvolená) a zkopírujte token – zobrazí se jen jednou. - První SMS.
Odpověď 202 znamená, že zpráva je uložená ve frontě.curl -si http://192.0.2.10/api/v1/sms \ -H "Authorization: Bearer sgw_0123456789abcdef0123456789abcdef" \ -H "Content-Type: application/json" \ -d '{"to":"+420600000001","text":"Test brany"}' HTTP/1.1 202 Accepted {"id":1,"status":"queued","parts":1,"encoding":"gsm7"} - Ověření. Stav zprávy uvidíte na stránce Messages → Sent and queued, nebo přes API:
curl -s http://192.0.2.10/api/v1/sms/1 -H "Authorization: Bearer sgw_…"(polestatus).
Dále: upozornění webhookem a e-mailem (kapitola 6), ochrana nákladů (kapitola 3).
Quick start
- Connect. Insert a SIM with an SMS service, connect the Ethernet cable and the power (PoE or USB).
- Find the address. The gateway gets its address from DHCP – look it up in the router's client list. A fresh device without an Ethernet link opens the open WiFi
SMS-GW-XXXXXXafter about 10 s; join it and openhttp://10.217.88.1/. - Password. Open
http://<gateway address>/and log in with an empty password. On a blank board format the storage first (the form at the top), then set the admin password (8–64 characters). - Check. After about a minute (the modem is switched on about 20 s after the start and then registers), check on the Status page that the modem is ready, the SIM is fine, it is registered with the network and has a signal.
- API key. On the API keys page create a key (the scopes
sendandreadare preselected) and copy the token – it is shown only once. - First SMS.
The answer 202 means the message is stored in the queue.curl -si http://192.0.2.10/api/v1/sms \ -H "Authorization: Bearer sgw_0123456789abcdef0123456789abcdef" \ -H "Content-Type: application/json" \ -d '{"to":"+420600000001","text":"Gateway test"}' HTTP/1.1 202 Accepted {"id":1,"status":"queued","parts":1,"encoding":"gsm7"} - Verify. See the message's state on the Messages page → Sent and queued, or through the API:
curl -s http://192.0.2.10/api/v1/sms/1 -H "Authorization: Bearer sgw_…"(thestatusfield).
Next: webhook and e-mail notifications (chapter 6), cost protection (chapter 3).
1. Přehled
Brána přijímá SMS přes vestavěný LTE modem a trvale je ukládá do vlastní flash paměti, odesílá SMS z trvalé fronty se stavem každé části a s doručenkami a nabízí podnikovým systémům stabilní REST API, podepsaný webhook a e-mailová upozornění. Produktem je API; webové rozhraní slouží ke správě.
Hardware
| Část | Popis |
|---|---|
| Deska | Gateway Pro, procesor ESP32-WROOM-32E, flash 16 MB; pro zprávy a nastavení oddíl LittleFS o velikosti asi 7,9 MB |
| Modem | SIMCom A7682E (LTE Cat-1), řízený jen AT příkazy; používá se pouze pro SMS, ne pro datové připojení |
| Ethernet | LAN8720A, 10/100 Mb/s; hlavní síťové připojení |
| WiFi | volitelný režim stanice (ve výchozím stavu vypnutý) a přístupový bod pro první nastavení / obnovu |
| Napájení | PoE nebo USB (přepínač napájení na desce); stránka Status ukazuje aktuální zdroj |
| Rádio LoRa | modul SX1262 na desce firmware nepoužívá; při startu ho uspí (Status: „LoRa radio: sleep“) |
Co brána umí
- příjem SMS včetně vícedílných zpráv, kódování GSM-7, UCS-2 i binárních zpráv, s trvalým uložením (zpráva se z modemu smaže až po uložení);
- odesílání z fronty: priorita, platnost (TTL), stav po částech, doručenky, opakování dočasných chyb;
- log odeslaných zpráv a schránku přijatých zpráv s potvrzováním (ack);
- REST API
/api/v1s klíči a oprávněními, ochranu nákladů (povolené předvolby, hodinové a denní limity); - webhook (HTTP nebo ověřené HTTPS, podpis HMAC-SHA256) a e-mail (STARTTLS, SMTPS nebo SMTP);
- webové rozhraní správce, aktualizaci firmwaru nahráním podepsaného obrazu s automatickým návratem při selhání.
Co brána neumí (mimo rozsah)
- LoRa, MQTT, datové připojení přes LTE (LTE není záložní uplink), více SIM, hovory (příchozí hovor se zavěsí), USSD;
- alfanumerického odesílatele: SMS odcházejí z čísla SIM;
- odhlašování příjemců (opt-out / STOP) řeší integrující systém;
- HTTPS server na zařízení: webové rozhraní i API jsou pouze HTTP (viz Bezpečnost);
- automatické aktualizace nebo stahování firmwaru z URL.
Propustnost je zhruba jedna část SMS za sekundu (omezení modemu), k tomu platí limity férového užívání operátora pro SIM. Doručení přijatých zpráv integraci i událostí webhooku je „alespoň jednou“ a pořadí není zaručeno. Stav sent bez delivered je normální konečný stav – operátor doručenku poslat nemusí.
1. Overview
The gateway receives SMS through its built-in LTE modem and stores them durably in its own flash memory, sends SMS from a persistent queue with the state of every part and delivery reports, and offers business systems a stable REST API, a signed webhook and e-mail notifications. The product is the API; the web interface is for administration.
Hardware
| Part | Description |
|---|---|
| Board | Gateway Pro, ESP32-WROOM-32E processor, 16 MB flash; a LittleFS partition of about 7.9 MB for messages and settings |
| Modem | SIMCom A7682E (LTE Cat-1), driven by AT commands only; used for SMS only, not as a data connection |
| Ethernet | LAN8720A, 10/100 Mb/s; the main network connection |
| WiFi | an optional station mode (off by default) and an access point for the first setup / recovery |
| Power | PoE or USB (a power multiplexer on the board); the Status page shows the current source |
| LoRa radio | the SX1262 module on the board is not used by this firmware; it is put to sleep at boot (Status: "LoRa radio: sleep") |
What the gateway does
- receives SMS, including multi-part messages, GSM-7, UCS-2 and binary messages, and stores them durably (a message is deleted from the modem only after it is stored);
- sends from a queue: priority, time to live (TTL), per-part state, delivery reports, retries of temporary errors;
- keeps a log of sent messages and an inbox of received messages with acknowledgements;
- REST API
/api/v1with keys and scopes; cost protection (allowed prefixes, hourly and daily limits); - webhook (HTTP or verified HTTPS, HMAC-SHA256 signature) and e-mail (STARTTLS, SMTPS or SMTP);
- admin web interface; firmware update by uploading a signed image, with automatic rollback on failure.
Out of scope
- LoRa, MQTT, LTE data (LTE is not a backup uplink), several SIMs, voice calls (an incoming call is hung up), USSD;
- alphanumeric sender: SMS are sent from the SIM's number;
- recipient opt-out (STOP) is handled by the integrating system;
- an HTTPS server on the device: the web interface and the API are plain HTTP only (see Security notes);
- automatic updates or firmware downloads from a URL.
Throughput is about one SMS part per second (a limit of the modem), plus the operator's fair-use limits for the SIM. Delivery of received messages to the integration and of webhook events is at least once, and the order is not guaranteed. sent without delivered is a normal final state: operators do not always send reports.
2. Instalace a první spuštění
Napájení a SIM
- Bránu napájejte přes PoE (ethernetový kabel z PoE switche nebo injektoru) nebo přes USB.
- Vložte SIM s aktivní službou SMS. Modem se zapne asi 20 s po startu brány. PIN SIM se zadává na stránce Network (viz níže); SIM bez PIN nepotřebuje nic.
Síť
- Ethernet je hlavní připojení, ve výchozím stavu s adresou z DHCP. Pevnou adresu nastavíte na stránce Network.
- WiFi stanice je volitelná a ve výchozím stavu vypnutá (ovladač zabírá asi 21 kB RAM). Když má Ethernet adresu, provoz jde přes Ethernet; WiFi se použije, jen když Ethernet adresu nemá.
- Čas: brána se synchronizuje přes NTP (
pool.ntp.org,time.cloudflare.com,time.google.com; NTP server oznámený přes DHCP nahradí první z nich). Dokud NTP neodpoví, převezme čas z mobilní sítě. Platný čas je nutný pro hodinové a denní limity odesílání a pro ověřené TLS. Povolte bráně odchozí NTP (UDP 123). - Webové rozhraní i API jsou na portu 80 (HTTP). Bránu provozujte v izolované síti / VLAN nebo za reverzní proxy s TLS (viz Bezpečnost).
- Podsíť 10.217.88.0/24 je vyhrazena pro přístupový bod brány: LAN ji nesmí používat (API klienty z ní odmítá).
Nové zařízení: přístupový bod pro nastavení
Zařízení bez hesla správce spustí otevřenou WiFi síť SMS-GW-XXXXXX (přípona z MAC adresy), pokud 10 s nemá link Ethernetu ani připojenou WiFi stanici. Připojte se k ní a otevřete http://10.217.88.1/ (DNS přístupového bodu odpovídá na každé jméno touto adresou, takže se stránka často otevře sama). Je-li připojen Ethernet, přístupový bod se nespustí – bránu pak najdete podle adresy přidělené DHCP serverem a otevřete ji v prohlížeči.
Dokud heslo správce není nastavené (nové zařízení nebo po příkazu reset-password), přihlásí se prázdným heslem kdokoli, kdo se k webovému rozhraní dostane – při spuštěném přístupovém bodu pro nastavení tedy kdokoli v dosahu jeho otevřené WiFi. Heslo nastavte ihned.
Postup prvního spuštění
- Přihlášení: bez nastaveného hesla se přihlásíte prázdným heslem. Každá stránka pak vede na stránku hesla.
- Nejdřív úložiště: když se oddíl úložiště nepřipojil (prázdná deska), stránka hesla nabídne nahoře formulář Format the storage. Zaškrtněte potvrzení, že formátování smaže vše na oddílu, a naformátujte. Pokud zařízení už dříve data mělo, nejdřív ho jednou restartujte – připojení může selhat i z přechodné příčiny a formátování data smaže. Brána nic neformátuje sama.
- Potom heslo správce (8 až 64 znaků). Heslo se ukládá do NVS mimo oddíl úložiště, takže se uloží i bez úložiště; nastavení, API klíče a zprávy se ale uložit nedají, dokud úložiště není naformátované – výsledná stránka to řekne.
- Přístupový bod, který běží ve chvíli nastavení hesla, běží dál, dokud se neobjeví lokální síť (link Ethernetu nebo připojená WiFi stanice); pak se zastaví a už se znovu nespustí. Na stránce Network nastavte síť.
- Dále: časové pásmo (System, výchozí
Europe/Prague), SIM PIN a APN (Network), API klíče, ochrana nákladů, upozornění.
Obnovovací přístupový bod
S nastaveným heslem správce se přístupový bod při výpadku linku nikdy nespustí. Volitelně (System → Recovery access point after boot, výchozí vypnuto) brána po každém startu otevře síť chráněnou WPA2 na 5 minut, déle jen dokud je připojeno zařízení, nejvýš 30 minut od startu. Heslo sítě je náhodné (16 znaků), vznikne na zařízení a zobrazí se jen přihlášenému správci na stránce System, kde lze vygenerovat nové. S heslem správce nesouvisí. Špatnou statickou adresu nebo VLAN tak opravíte po vypnutí a zapnutí brány.
- Klientům přístupového bodu se REST API nikdy neposkytuje (403).
- Přístupový bod zabírá asi 30 kB paměti; upozornění (webhook, e-mail) mezitím čekají a odejdou po jeho zastavení.
- Bez obnovovacího přístupového bodu se špatné nastavení sítě opraví příkazem
reset-networkna sériové konzoli (viz Diagnostika).
2. Installation and first start
Power and SIM
- Power the gateway over PoE (the Ethernet cable from a PoE switch or injector) or over USB.
- Insert a SIM with an active SMS service. The modem is switched on about 20 s after the gateway starts. A SIM PIN is entered on the Network page (below); a SIM without a PIN needs nothing.
Network
- Ethernet is the main connection, by default with an address from DHCP. A static address is set on the Network page.
- WiFi station is optional and off by default (the driver takes about 21 kB of RAM). While Ethernet has an address, traffic goes over Ethernet; WiFi is used only when Ethernet has none.
- Time: the gateway synchronises over NTP (
pool.ntp.org,time.cloudflare.com,time.google.com; an NTP server announced by DHCP takes the place of the first one). Until NTP answers it takes the time from the mobile network. A valid clock is required for the hourly and daily sending limits and for verified TLS. Allow outgoing NTP (UDP 123) for the gateway. - The web interface and the API are on port 80 (HTTP). Run the gateway in an isolated network / VLAN or behind a TLS reverse proxy (see Security notes).
- The subnet 10.217.88.0/24 is reserved for the gateway's access point: the LAN must not use it (the API refuses clients from it).
Fresh device: the setup access point
A device without an admin password opens an open WiFi network SMS-GW-XXXXXX (the suffix comes from the MAC address) when it has had neither an Ethernet link nor a connected WiFi station for 10 s. Join it and open http://10.217.88.1/ (the access point's DNS answers every name with this address, so the page often opens by itself). With Ethernet connected the access point does not start: find the gateway by the address the DHCP server gave it and open it in a browser.
While no admin password is set (a fresh device, or after the reset-password command), anyone who reaches the web interface logs in with an empty password – with the setup access point running, that is anyone in range of its open WiFi. Set the password at once.
First-start flow
- Log in: without a password set, log in with an empty password. Every page then leads to the password page.
- The storage first: when the storage partition did not mount (a blank board), the password page offers the Format the storage form at the top. Tick the confirmation that formatting erases everything on the partition, and format. If the device held data before, restart it once first – a mount can fail for a passing reason and formatting erases the data. The gateway never formats by itself.
- Then the admin password (8 to 64 characters). The password is kept in NVS, outside the storage partition, so it is saved even without the storage; settings, API keys and messages cannot be saved until the storage is formatted – the result page says so.
- An access point that runs when the password is set keeps running until local network access appears (an Ethernet link or a connected WiFi station); then it stops and never starts again. Set up the network on the Network page.
- Next: the time zone (System, default
Europe/Prague), the SIM PIN and APN (Network), API keys, cost protection, notifications.
Recovery access point
With an admin password set, the access point never starts on a link loss. Optionally (System → Recovery access point after boot, off by default) the gateway opens a WPA2 network for 5 minutes after every start, longer only while a device is connected, at most 30 minutes after the start. Its passphrase is random (16 characters), made on the device, and shown only to the logged-in admin on the System page, where a new one can be generated. It has nothing to do with the admin password. A wrong static address or VLAN is then fixed by a power cycle.
- The REST API is never served to access point clients (403).
- The access point takes about 30 kB of memory; notifications (webhook, e-mail) wait meanwhile and go out once it stops.
- Without the recovery access point a wrong network setting is fixed with
reset-networkon the serial console (see Diagnostics).
3. Webové rozhraní správce
Webové rozhraní je v angličtině; názvy stránek, polí a tlačítek zde uvádíme tak, jak jsou na obrazovce.
Rozhraní běží na http://<adresa brány>/ (port 80). Jeden účet správce s heslem; relace je náhodný token v cookie s příznaky HttpOnly a SameSite=Strict, drží se jen v RAM (restart všechny odhlásí), nejvýš 4 současné relace, relace vyprší po 24 h nečinnosti. Pět chybných hesel z jedné adresy ji zablokuje na 60 s; po 10 chybách za minutu celkem se pokusy omezí na jeden za sekundu. Heslo se ukládá jako PBKDF2-HMAC-SHA256 s náhodnou solí.
Každý formulář, který něco mění, nese token relace (ochrana CSRF); požadavek ze stránky jiného webu se odmítne. Za reverzní proxy zachovejte hlavičku Host – formulář, jehož Origin neodpovídá Host, se odmítne (403). Veškerý text pocházející ze zpráv se zobrazuje jako prostý text; řídicí znaky směru textu (bidi) se ukazují viditelně, např. [U+202E], a neuplatní se.
Status
Nahoře alarmy: co je špatně, co to znamená pro zprávy a odkaz na stránku, kde se to řeší. Například: nepřipojené úložiště, úložiště zpráv se neotevřelo (chyba čtení), úložiště se znovu sestavuje po startu, storage.error (selhal zápis), storage.state_lost, storage.missing_message, storage.corrupt, inbox.evicted (nepotvrzené zprávy vyřazené kvótou nebo stářím), queue.full, modem vypnutý nebo nemůže odesílat, SIM bez čísla SMS centra, plné úložiště zpráv v modemu, neplatný čas (limity zamrzlé), dosažený globální limit, běžící obnovovací přístupový bod, TLS bez ověření, selhávající webhook nebo e-mail, stav aktualizace firmwaru. Alarmy úložiště zůstávají, dokud je nesmažete tlačítkem Clear the storage alarms nebo do restartu; nový problém je zvedne znovu.
Dále přehled: firmware, doba běhu, příčina posledního restartu, čas a jeho zdroj (NTP / mobilní síť), zdroj napájení, paměť (volná, největší blok, minimum), instance_id; modem (stav, SIM, síť, signál, úložiště zpráv); úložiště zpráv (přijaté, odeslané, fronty, oddíl, zápisy do flash); REST API (klíče, požadavky, odmítnuté, 503, odeslané části); upozornění; síť (uplink, link a rychlost Ethernetu, DHCP / statická adresa, IP, výchozí brána, WiFi, přístupový bod, rádio LoRa).
Messages
- Received – přijaté zprávy od nejnovější, 50 na stránku (odkaz Older). Detail zprávy ukáže části a text a umožní zprávu potvrdit (ack), stejně jako
POST /api/v1/inbox/ack. - Sent and queued – na první stránce fronta, pak log odeslaných od nejnovější. Detail ukáže stav každé části, doručenku, klíč (
key_id) aref; zprávu ve frontě lze zrušit (zruší se části, které ještě čekají). - Dlouhý text se v detailu může zkrátit s poznámkou; celý je v API.
Send test SMS
Zkušební SMS jde přesně cestou POST /api/v1/sms: stejná kontrola, ochrana nákladů (povolené předvolby, výjimky, globální limity) a fronta. Pole: příjemce (mezinárodní formát), text, kódování (auto / GSM-7 / UCS-2), požadavek na doručenku. Zpráva se zaznamená s klíčem „web“ (v API key_id: null) a ref „web“ a počítá se jen do globálních limitů. Druhé odeslání téhož formuláře (obnovení stránky, dvojklik) nevytvoří druhou zprávu. Odeslání, potvrzení a zrušení sdílejí s API dvě zápisové úlohy: při zátěži z API může stránka odpovědět „busy, try again“.
API keys
- Nový klíč
- Název (1–24 bajtů UTF-8; s diakritikou se vejde méně znaků), oprávnění
send/read/admin, volitelně vlastní limity částí za hodinu a za den (0 = jen globální limit). Nejvýš 4 klíče. Token se zobrazí jen jednou při vytvoření; brána si ponechá jen jeho SHA-256. - Existující klíč
- Id (
key_id0–3), oprávnění, vytvořen, naposledy použit, vlastní limity (lze změnit), tlačítko Revoke (zneplatní token okamžitě).
Bez klíčů API odmítá vše kromě GET /api/v1/healthz.
Cost protection
- Allowed prefixes
- Povolené předvolby, oddělené čárkou (výchozí
+420); nejvýš 8 předvoleb, každá nejvýš 8 znaků (+a číslice). Ostatní čísla se odmítnou. - Explicit exceptions
- Výslovně povolená prémiová, zvláštní nebo krátká čísla či rozsahy: nejvýš 8 položek, každá nejvýš 16 znaků (
+a číslice); výjimka platí pro každé číslo, které jí začíná. Pod +420 projdou bez výjimky jen běžná čísla: 9 číslic začínajících 2–5 (pevné linky) nebo 6–7 (mobilní a běžná negeografická) kromě 700 (osobní čísla, přesměrovaná kamkoli si držitel zvolí); vše ostatní (700, 0xx, 1xx, 8xx, 9xx – osobní, prémiová, se zvláštním tarifem, VoIP, privátní sítě – a krátká či neúplná čísla) se odmítne. - Global parts per hour / per day
- Globální limity částí (výchozí 200 za hodinu, 1 000 za den; 0 = bez limitu).
Pod jakoukoli jinou povolenou předvolbou se kontroluje jen délka čísla: ochrana proti prémiovým číslům tam není.
Stránka ukazuje odeslané části v této hodině a dnes.
Notifications
Nastavení webhooku a e-mailu, popsané podrobně v kapitole Webhook a e-mailová upozornění. Oba kanály jsou ve výchozím stavu vypnuté (volba Enabled). U každého kanálu je jeho stav (stav, nevyřízené události, doručené / neúspěšné pokusy, poslední chyba, poslední úspěch), tlačítko pro zkušební událost / e-mail a formulář pro vlastní CA.
Network
- Ethernet
- Adresování DHCP nebo Static (IP adresa, maska, výchozí brána, DNS 1 – prázdné = výchozí brána, DNS 2 volitelný). Adresy se kontrolují (brána v podsíti, adresa není adresou sítě ani broadcastu). Save and restart – brána se restartuje.
- WiFi station
- Use WiFi, název sítě (SSID, max. 32 bajtů), heslo (8–63 tisknutelných znaků ASCII nebo 64 hexadecimálních číslic; prázdné pole u stejné sítě ponechá uložené heslo, u nové sítě znamená otevřenou síť). Při výpadku se stanice znovu připojuje každých 60 s. Otevřený přístupový bod pro nastavení se může spustit jen na zařízení bez hesla správce (nové, nebo po
reset-passwordna sériové konzoli), a to asi po 10 s bez linku Ethernetu a bez připojené WiFi stanice – nastavená, ale nepřipojená WiFi ho nezastaví. Jakmile běží, zůstane zapnutý (i po nastavení hesla), dokud link nebo připojená stanice nevydrží asi 5 s. Uloží se s restartem. - LTE modem
- Modem enabled (výchozí zapnuto; vypnutí a zapnutí platí hned), APN (prázdné = od sítě), SIM PIN (4–8 číslic; prázdné = ponechat uložený), Remove the stored PIN. APN a PIN platí při příštím startu modemu. PIN se posílá jen jednou: když ho SIM odmítne, brána ho znovu nepošle, dokud nezadáte nový (stránka na to upozorní).
System
- Storage
- Jen když oddíl není připojený: formulář pro formátování s potvrzením (a rada: pokud zařízení už data mělo, nejdřív ho jednou restartujte).
- Time zone
- Časové pásmo (výchozí Europe/Prague) pro čas na stránce Status a časová razítka v logu. Stránky zpráv a klíčů, API i upozornění uvádějí čas v UTC.
- Admin password
- Změna hesla (vyžaduje současné heslo).
- Recovery access point
- Název sítě, heslo (passphrase), Generate a new passphrase, přepínač Recovery access point after boot (uloží se s restartem).
- Restart
- Řízený restart brány. Pokud nový firmware ještě čeká na ověření, restart na něj počká (nejvýš 180 s od první žádosti), viz Aktualizace firmwaru.
Firmware
Běžící verze, podpis nainstalovaného obrazu, podpisové klíče, stav ověření nového firmwaru, poslední instalace; nahrání obrazu (.bin), potvrzení obrazu, který na potvrzení čeká, a přepínač Signed images only. Podrobnosti v kapitole Aktualizace firmwaru.
Logs
Záznamy od nejnovějšího, filtr úrovně (Errors, Warnings and errors, Info and above, Debug and above, All), volitelné automatické obnovení po 10, 30 nebo 60 s, tlačítko Clear. Texty zpráv se do logu nikdy nezapisují; telefonní čísla jen maskovaná (např. +420******123), alfanumerický odesílatel celý. Log je v RAM a restart ho smaže; stejné řádky jdou i na sériovou konzoli.
3. Admin web interface
The web interface is in English; the names of pages, fields and buttons are given here as they appear on the screen.
The interface runs at http://<gateway address>/ (port 80). One admin account with a password; a session is a random token in an HttpOnly, SameSite=Strict cookie, kept in RAM only (a restart logs everyone out), at most 4 sessions at a time, a session expires after 24 h without use. Five wrong passwords from one address lock it for 60 s; after 10 failures within a minute in all, attempts are limited to one a second. The password is stored as PBKDF2-HMAC-SHA256 with a random salt.
Every form that changes something carries the session's form token (CSRF protection); a request from another site's page is refused. Behind a reverse proxy keep the Host header – a form whose Origin does not match Host is refused (403). Every text that comes from a message is shown escaped; bidirectional control characters are shown visibly, e.g. [U+202E], not applied.
Status
Alarms first: what is wrong, what it means for the messages, and a link to the page that deals with it. For example: the storage not mounted, the message store not opened (read error), the store being rebuilt after the start, storage.error (a write failed), storage.state_lost, storage.missing_message, storage.corrupt, inbox.evicted (unacknowledged messages removed by the quota or by age), queue.full, the modem switched off or unable to send, the SIM without an SMS centre number, the modem's message storage full, no valid clock (limits frozen), the global limit reached, the recovery access point running, TLS without verification, a failing webhook or e-mail channel, the state of a firmware update. The storage alarms stay until they are cleared with Clear the storage alarms or until a restart; a new problem raises them again.
Then the overview: firmware, uptime, the reason for the last restart, the time and its source (NTP / mobile network), the power source, memory (free, largest block, lowest), instance_id; the modem (state, SIM, network, signal, message storage); the message store (received, sent, queues, partition, flash writes); the REST API (keys, requests, refused, 503, parts sent); notifications; the network (uplink, Ethernet link and speed, DHCP / static, IP, default gateway, WiFi, access point, LoRa radio).
Messages
- Received – received messages, newest first, 50 a page (link Older). The detail of a message shows its parts and text and lets you acknowledge it, like
POST /api/v1/inbox/ack. - Sent and queued – the queue on the first page, then the sent log, newest first. The detail shows the state of every part, the delivery report, the key (
key_id) andref; a queued message can be cancelled (the parts still waiting are cancelled). - A long text may be shortened in the detail, with a note; the full text is in the API.
Send test SMS
A test SMS takes exactly the path of POST /api/v1/sms: the same validation, the cost protection (allowed prefixes, exceptions, the global limits) and the queue. Fields: the recipient (international format), the text, the encoding (auto / GSM-7 / UCS-2), a delivery report request. The message is recorded with key "web" (key_id: null in the API) and ref "web" and counts against the global limits only. Submitting the same form twice (a reload, a double click) does not create a second message. Send, acknowledge and cancel share the two write jobs with the API: under API load the page may answer "busy, try again".
API keys
- New key
- A name (1–24 bytes of UTF-8; fewer characters with accents), the scopes
send/read/admin, optionally its own part limits per hour and per day (0 = the global limit only). At most 4 keys. The token is shown once, when the key is created; the gateway keeps only its SHA-256. - An existing key
- Id (
key_id0–3), scopes, created, last used, its own limits (editable), and Revoke (the token is refused at once).
Without keys the API refuses everything but GET /api/v1/healthz.
Cost protection
- Allowed prefixes
- Comma separated (default
+420); at most 8 prefixes of at most 8 characters each (+and digits). Other numbers are refused. - Explicit exceptions
- Premium, special-rate or short numbers or ranges allowed explicitly: at most 8 entries of at most 16 characters each (
+and digits); an exception covers every number that starts with it. Under +420 only ordinary numbers pass without an exception: 9 digits starting 2–5 (geographic) or 6–7 (mobile and ordinary non-geographic) except 700 (personal numbers, forwarded wherever the holder chooses); everything else (700, 0xx, 1xx, 8xx, 9xx – personal, premium, special rate, VoIP, private networks – and short or incomplete numbers) is refused. - Global parts per hour / per day
- Global part limits (defaults 200 an hour, 1,000 a day; 0 = no limit).
Under any other prefix you allow only the length of the number is checked: there is no premium protection there.
The page shows the parts sent this hour and today.
Notifications
The webhook and e-mail settings, described in detail in Webhook and e-mail notifications. Both channels are off by default (the Enabled checkbox). Each channel shows its status (state, backlog, delivered / failed attempts, last error, last success), a button for a test event / e-mail, and the form for an own CA.
Network
- Ethernet
- Addressing DHCP or Static (IP address, subnet mask, gateway, DNS 1 – empty = the gateway, DNS 2 optional). The addresses are checked (the gateway in the subnet, the address is neither the network nor the broadcast address). Save and restart – the gateway restarts.
- WiFi station
- Use WiFi, the network name (SSID, at most 32 bytes), the password (8–63 printable ASCII characters or 64 hex digits; an empty field keeps the stored password for the same network and means an open network for a new one). While down, the station reconnects every 60 s. The open setup access point can start only on a device without an admin password (a new one, or after
reset-passwordon the serial console), after about 10 s without an Ethernet link and without a connected WiFi station – a configured WiFi network that is not connected does not stop it. Once running it stays up (also after the password is set) until a link or a station has held for about 5 s. Saved with a restart. - LTE modem
- Modem enabled (on by default; switching it on or off applies at once), APN (empty = from the network), SIM PIN (4–8 digits; empty = keep the stored one), Remove the stored PIN. The APN and the PIN apply at the next start of the modem. The PIN is sent once: when the SIM refuses it, the gateway does not send it again until you enter a new one (the page says so).
System
- Storage
- Only while the partition is not mounted: the format form with its confirmation (and the advice: if the device held data, restart it once first).
- Time zone
- The time zone (default Europe/Prague) of the time on the Status page and of the log time stamps. The message and key pages, the API and the notifications give times in UTC.
- Admin password
- Change the password (needs the current one).
- Recovery access point
- Network name, passphrase, Generate a new passphrase, the switch Recovery access point after boot (saved with a restart).
- Restart
- A controlled restart of the gateway. While a new firmware still waits for its validation, the restart waits for it (at most 180 s from the first request), see Firmware updates.
Firmware
The running version, the signature of the installed image, the signing keys, the validation state of a new firmware, the last install; the image upload (.bin), the confirmation of an image that waits for it, and the switch Signed images only. Details in Firmware updates.
Logs
Entries newest first, a level filter (Errors, Warnings and errors, Info and above, Debug and above, All), an optional auto-refresh every 10, 30 or 60 s, and Clear. Message texts are never logged; phone numbers only masked (e.g. +420******123), an alphanumeric sender as it is. The log is kept in RAM and a restart clears it; the same lines go to the serial console.
4. Zprávy
Příjem
- Brána čte úložiště zpráv modemu (paměť modemu každých 60 s a ihned po oznámení nové zprávy nebo doručenky, SIM každých 10 minut) a dekóduje každou PDU.
- Nejdřív uložit, pak smazat: zpráva se trvale zapíše do úložiště brány a teprve potom (po dalším úplném výpisu, který ji ukázal beze změny) se smaže z modemu. Duplicitní PDU se rozpozná a neuloží podruhé.
- Ukládá se surové TPDU (bez adresy SMSC) a metadata; text se dekóduje při čtení. Podporuje se GSM-7 včetně rozšířené tabulky, UCS-2, binární zprávy (
encoding: "binary", hex v polidata) a alfanumerický odesílatel. - Při chybě zápisu (ne kvóty) zůstanou zprávy v modemu a zvedne se alarm
storage.error; nic se nezahodí.
Vícedílné zprávy
- Části se skládají podle odesílatele a reference zprávy (8bitové i 16bitové reference). Do složení se drží nejvýš 64 rozpracovaných částí.
- Nepřijdou-li všechny části do 1 hodiny, uloží se zpráva s tím, co přišlo, jako neúplná (
complete: false); později došlé části tvoří další neúplnou zprávu. Při plném prostoru pro skládání se nejstarší skupina uzavře jako neúplná.
Úložiště, retence a vyřazování
- Archiv přijatých a odeslaných zpráv zabírá nejvýš asi 3,5 MB, v poměru přijaté : odeslané = 55 : 45. Přijatých se vejde zhruba 10 až 15 tisíc běžných SMS.
- Retence podle stáří: 90 dní (posuzuje se jen při platném čase). Při překročení kvóty, stáří, více než 32 768 živých id přijatých zpráv nebo zaplnění tabulky segmentů se vyřadí nejstarší segment archivu (nikdy ne ten nejnovější).
- Vyřazení maže i nepotvrzené přijaté zprávy: pak se zvedne alarm
inbox.evicteda zvýší se čítačstorage.unacked_evicted. Integrace proto musí zprávy potvrzovat. - Id zpráv rostou monotónně.
instance_id(16 hex číslic) se změní, když se úložiště naformátuje nebo začne znovu; deduplikujte vždy podleinstance_id+id.
Odesílání a fronta
POST /api/v1/sms(nebo Send test SMS) zprávu trvale uloží do fronty, než odpoví202. Fronta má kapacitu 150 zpráv po nejvýš 10 částech.- Odesílá se vždy jedna část naráz: nejdřív priorita
high, pak nejstarší. Modem odešle zhruba jednu část za sekundu. - Před odesláním části se trvale zapíše stav
sending. Restart během odesílání proto udělá z částiunknown– nikdy duplikát. Částunknownbrána nikdy sama neodešle znovu. - Chyby: chyba, která prokazuje neodeslání, se opakuje s exponenciálním odstupem (nejvýš 5 pokusů celkem, u kódu 38 dva); trvalá chyba →
failed; nejednoznačný výsledek (vypršení času, neznámý kód) →unknown. Čekání na odpověď modemu je nejvýš 120 s. - Když se část neodešle (
failed,expired,unknown), další části téže zprávy se už neposílají (skipped) – neplatí se za zprávu, kterou si telefon nesloží. - Bez sítě nebo SIM fronta čeká a pokusy se nečerpají. Části neodeslané do
ttl(výchozí 1 h, nejvýš 72 h) skončí jakoexpired.validity(výchozí 24 h, nejvýš 72 h) určuje, jak dlouho se o doručení snaží síť.
Doručenky
- Se
report: truebrána žádá síť o doručenky a páruje je s odeslanými částmi (reference zprávy, příjemce, čas). Čeká se až dosent_at + validity + 1 h; potom je stavsentkonečný. - Tabulka čekajících doručenek má 384 položek; při zaplnění se nejstarší zahodí (zpráva zůstane
sent).
Limity a ochrana nákladů
- Číslo musí začínat povolenou předvolbou; pod +420 projdou jen běžná pevná a mobilní čísla (ne 700 – osobní čísla), ostatní jen jako výslovné výjimky (viz Cost protection). Odmítnutí: 422
number_not_allowed, nic se nezařadí. - Limity počítají části za hodinu a za den, globálně a pro každý klíč. Do limitu se počítají části odeslané v aktuální hodině / dni (i
unknown– mohla být účtována), části čekající ve frontě a nová zpráva. Překročení: 429limit_exceededsRetry-Afterdo další hodiny / dne (UTC). - Bez platného času (ani NTP, ani čas mobilní sítě) se čítače nepřetočí: po dosažení limitu odpovídá
POST /sms429, dokud čas není platný. Čítače se ukládají, restart je nevynuluje.
4. Messages
Receiving
- The gateway reads the modem's message storage (the modem memory every 60 s and at once when a new message or report is announced, the SIM every 10 minutes) and decodes every PDU.
- Store, then delete: a message is written durably into the gateway's storage and only then (after a later complete listing showed it unchanged) deleted from the modem. A duplicate PDU is recognised and not stored twice.
- The raw TPDU (without the SMSC address) and metadata are stored; the text is decoded when it is read. GSM-7 including the extension table, UCS-2, binary messages (
encoding: "binary", hex indata), alphanumeric senders. - On a write error (not the quota) the messages stay in the modem and the alarm
storage.erroris raised; nothing is dropped.
Multi-part messages
- Parts are joined by sender and message reference (8-bit and 16-bit references). At most 64 parts are held for joining.
- When not every part arrives within 1 hour, the message is stored with what came, as incomplete (
complete: false); parts arriving later form another incomplete message. When the joining space is full, the oldest group is closed as incomplete.
Storage, retention and eviction
- The archive of received and sent messages takes at most about 3.5 MB, received : sent = 55 : 45. The received part holds roughly 10 to 15 thousand ordinary SMS.
- Retention by age: 90 days (judged only with a valid clock). Over the quota or the age, with more than 32,768 live received ids, or with the segment table full, the oldest archive segment is removed (never the newest one).
- Eviction also removes unacknowledged received messages: the alarm
inbox.evictedis raised and the counterstorage.unacked_evictedis incremented then. Integrations must therefore acknowledge. - Message ids grow monotonically.
instance_id(16 hex digits) changes when the storage is formatted or starts anew; always deduplicate byinstance_id+id.
Sending and the queue
POST /api/v1/sms(or Send test SMS) stores the message durably in the queue before it answers202. The queue holds 150 messages of at most 10 parts.- One part is sent at a time: priority
highfirst, then the oldest. The modem sends about one part a second. - Before a part is sent, the state
sendingis written durably. A restart during a send therefore makes the partunknown– never a duplicate. The gateway never sends anunknownpart again by itself. - Errors: an error that proves the part was not sent is retried with exponential backoff (at most 5 attempts in all, 2 for code 38); a permanent error →
failed; an ambiguous outcome (timeout, unknown code) →unknown. The modem's answer is awaited at most 120 s. - When a part is not sent (
failed,expired,unknown), the remaining parts of that message are not sent (skipped) – no use paying for a message the phone cannot join. - Without network or SIM the queue waits and no attempts are used. Parts not sent within
ttl(default 1 h, at most 72 h) endexpired.validity(default 24 h, at most 72 h) is how long the network tries to deliver.
Delivery reports
- With
report: truethe gateway asks the network for delivery reports and matches them to the sent parts (message reference, recipient, time). It waits untilsent_at + validity + 1 h; after thatsentis final. - The table of awaited reports has 384 entries; when it is full the oldest is dropped (the message stays
sent).
Limits and cost protection
- The number must start with an allowed prefix; under +420 only ordinary geographic and mobile numbers pass (not 700 – personal numbers), others only as explicit exceptions (see Cost protection). Refused: 422
number_not_allowed, nothing is queued. - The limits count parts per hour and per day, globally and per key. Counted are the parts sent in the current hour / day (also
unknown– it may have been billed), the parts still queued, and the new message. Over the limit: 429limit_exceededwithRetry-Afteruntil the next hour / day (UTC). - Without a valid clock (neither NTP nor the mobile network's time) the counters do not roll over: once a limit is reached,
POST /smsanswers 429 until the time is valid. The counters are persisted; a restart does not clear them.
5. REST API
JSON nad HTTP s prefixem /api/v1. Úplnou referenci všech endpointů, polí a chybových kódů obsahuje soubor docs/openapi.yaml (OpenAPI 3.1), který je součástí zdrojových kódů firmwaru; tato kapitola je jeho shrnutím. API se nikdy neposkytuje klientům přístupového bodu brány.
Autentizace a oprávnění
Token (sgw_ + 32 hexadecimálních číslic, 128 náhodných bitů) vznikne na stránce API keys a zobrazí se jednou. Posílá se v každém požadavku:
Authorization: Bearer sgw_0123456789abcdef0123456789abcdef
| Oprávnění | Povoluje |
|---|---|
send | POST /sms, POST /sms/{id}/cancel |
read | GET /status, /sms, /sms/active, /sms/{id}, /inbox, /inbox/{id}, POST /inbox/ack |
admin | vše |
- Zneplatněný klíč se odmítne okamžitě. Ztracený token nelze znovu zobrazit: klíč zneplatněte a vytvořte nový.
key_idu zpráv je slot klíče (0–3); slot se po zneplatnění znovu použije.- Požadavky bez platného tokenu dostanou 401 a sdílejí jeden globální rozpočet (10 najednou, pak jeden za 2 s); nad něj 429 s
Retry-After. Požadavek s platným tokenem na tento rozpočet nikdy nečeká. - Limity odesílání pro klíč (části za hodinu / den) se nastavují u klíče; globální na stránce Cost protection.
- Nová TCP spojení jsou omezena na 40 za sekundu celkem a 30 za sekundu z jedné adresy (nárazově 80 / 60); spojení nad limit se hned ukončí. Klienti za jednou proxy sdílejí její limit.
Endpointy
Cesty jsou relativní k /api/v1 (např. GET /api/v1/healthz).
| Metoda a cesta | Oprávnění | Účel |
|---|---|---|
GET /healthz | žádné | 200 {"status":"ok"}, když úložiště zpráv funguje; 503 během obnovy po startu nebo při chybě úložiště. Modem do toho nepatří. |
GET /status | read | firmware, api_version, instance_id, čas, modem, fronty, úložiště, alarmy, stav webhooku a e-mailu, paměť, čítače |
POST /sms | send | zařadí zprávu (202 až po trvalém uložení) |
GET /sms | read | log odeslaných v pořadí archivace; cursor (= next_cursor předchozí stránky), limit, ref; from / to = časové okno vytvoření zprávy (ISO-8601 s Z nebo posunem, nebo datum = 00:00 UTC; from včetně, to bez) |
GET /sms/active | read | fronta a části čekající na doručenky |
GET /sms/{id} | read | jedna odeslaná zpráva se všemi částmi |
POST /sms/{id}/cancel | send | zruší části, které ještě čekají |
GET /inbox | read | přijaté zprávy od nejstarší podle id; since_id, limit, unacked=1 |
GET /inbox/{id} | read | jedna přijatá zpráva; raw=1 vrátí uložená TPDU (hex) místo textu |
POST /inbox/ack | read | potvrdí přijaté zprávy ({"ids":[...]}, nejvýš 50) |
Stránkování: limit 1–50 (výchozí 20), stránka nejvýš 8 kB – může skončit dřív s has_more: true.
Odeslání zprávy
curl -si http://gateway.example.com/api/v1/sms \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-4711-sms" \
-d '{"to":"+420600000001","text":"Vaše objednávka 4711 je připravena.","report":true,"ref":"order-4711"}'
HTTP/1.1 202 Accepted
{"id":1234,"status":"queued","parts":1,"encoding":"ucs2"}
| Pole | Význam |
|---|---|
to | mezinárodní číslo (+ nebo 00, 8–15 číslic; mezery, -, ., (, ) se odstraní). Národní a krátká čísla se neposílají. |
text | UTF-8. Nejvýš 10 částí: 1 530 septetů GSM-7 (znak rozšířené tabulky jako € [ ] { } ~ ^ \ | zabírá dva) nebo 670 jednotek UCS-2. Delší: 422 text_too_long. |
encoding | auto (výchozí: GSM-7, pokud to jde, jinak UCS-2), gsm7, ucs2 |
report | žádat doručenky (výchozí false) |
validity | sekundy 60–259 200, výchozí 86 400 (24 h): jak dlouho doručuje síť |
ttl | sekundy 60–259 200, výchozí 3 600 (1 h): neodeslané části potom vyprší |
priority | high nebo normal (výchozí) |
ref | vlastní reference klienta (nejvýš 64 bajtů), filtr v logu odeslaných |
- 202 znamená uloženo: zpráva i záznam ve frontě jsou na flash dřív, než přijde odpověď; výpadek napájení po 202 ji neztratí. Odpověď 4xx / 5xx znamená, že se nic nezařadilo.
encoding: "gsm7"s textem, který GSM-7 neumí zapsat: 422not_gsm7.- Neznámá pole, pole uvedené dvakrát, špatné typy: 400. Tělo nejvýš 4 096 bajtů (413) a
Content-Type: application/json(415). - Modem může být nedostupný (bez sítě, bez SIM): zpráva se přesto zařadí a čeká; stav modemu ukáže
/status.
Idempotence – opakování bez duplikátů
- Posílejte s každým
POST /smshlavičkuIdempotency-Key(1–64 tisknutelných znaků ASCII, jedinečná pro zprávu, např. id objednávky). - Stejný klíč se stejným požadavkem do 24 hodin vrátí původní odpověď 202 s hlavičkou
Idempotent-Replayed: true; nic nového se nezařadí. Stejný klíč s jiným požadavkem: 422idempotency_conflict. - Klíče patří API klíči, který je použil. Požadavky se porovnávají po normalizaci (zápis čísla, pořadí polí, výchozí hodnoty). Brána si pamatuje posledních 500 zpráv s klíčem.
- Zprávu ve stavu
unknownbrána znovu neodešle. Chcete-li to zkusit znovu, pošlete nový požadavek s novým klíčem – a jen pokud je duplikát přijatelný.
Stavy zpráv
status | Konečný | Význam |
|---|---|---|
canceled | ano | zrušeno dřív, než se cokoli odeslalo |
sending | ne | část se odesílá, nebo jsou některé části odeslané a jiné čekají |
queued | ne | nic neodesláno, čeká se |
unknown | ano | nic potvrzeně neodesláno a výsledek části není znám – mohla, nebo nemusela odejít; nikdy se neodesílá znovu |
failed / expired | ano | nic neodesláno: síť trvale odmítla / uplynul ttl |
partially_sent | ano | některé části odeslány, zbytek ne |
undelivered | ano | vše odesláno, doručenka hlásí nedoručení části |
delivered | ano | vše odesláno a doručeno |
sent | ano / ne | vše odesláno; konečný bez report nebo po uplynutí lhůty pro doručenky |
Zpráva má mimo jiné id, to, status, final, created_at (null bez platného času), key_id (slot klíče, null pro zprávy brány a stránky Send test SMS), ref a pole parts. U každé části: state (queued, sending, sent, failed, expired, unknown, skipped, canceled), attempts, mr (reference sítě), sent_at, report (none, awaiting, delivered, pending, failed, dropped), report_status a error_code. Po alarmu poškození úložiště (storage.corrupt / storage.state_lost) označí brána všechny části, které ještě nebyly v konečném stavu, jako unknown – pak to může znamenat i „nikdy neodesláno“; nikdy to neznamená „odesláno dvakrát“.
POST /sms/{id}/cancel vrátí 200 {"id":…, "status":"canceled"|"partially_sent", "canceled_parts":n}; 409, když se část právě odesílá nebo už nic nečeká.
Příjem: čtení schránky a potvrzování
since = <poslední zpracované id, na začátku 0>
opakovat:
page = GET /api/v1/inbox?since_id={since}&limit=50
pro m v page.messages: # od nejstarší
zpracuj(m) # idempotentně: doručení alespoň jednou
ack.append(m.id)
POST /api/v1/inbox/ack {"ids": ack} # nejvýš 50 v jednom volání
since = page.next_since_id
pokud není page.has_more: počkej (interval dotazování)
sinceukládejte až po úspěšném potvrzení; po pádu se zpráva může objevit znovu – deduplikujte podleinstance_id+id.- Jednodušší alternativa:
GET /inbox?unacked=1vrací jen nepotvrzené zprávy. - Potvrzení id, které už neexistuje, se ignoruje. Odpověď:
{"acked": n}(zprávy, které předtím potvrzené nebyly). - Zpráva obsahuje
from,received_at(čas brány, UTC),scts(časové razítko sítě s posunem odesílatele),time_valid,encoding,parts,total(ohlášený počet částí u vícedílné zprávy),complete,ackedatext(nebodatau binární zprávy).
{"messages":[{"id":1201,"from":"+420600000002","received_at":"2026-11-24T12:00:58Z",
"time_valid":true,"scts":"2026-11-24T13:00:55+01:00","encoding":"ucs2",
"parts":1,"complete":true,"acked":false,"text":"Dobrý den"}],
"has_more":false,"next_since_id":1201}
Chybové kódy
Každá chyba má tvar {"error":{"code":"...","message":"..."}}. Programujte proti code (stabilní); message je pro lidi.
| HTTP | code | Kdy / co dělat |
|---|---|---|
| 400 | invalid_json, invalid_request, invalid_parameter, invalid_cursor, invalid_idempotency_key | neplatný JSON, chybějící / neznámé pole, špatný parametr, cizí kurzor, špatná hlavička |
| 401 | unauthorized | chybí / neznámý / zneplatněný token |
| 403 | forbidden | klíč nemá oprávnění, nebo je klient na přístupovém bodu brány |
| 404 | not_found | zpráva neexistuje (nebo ji odstranila retence) |
| 405 | method_not_allowed | viz hlavička Allow |
| 409 | conflict | zrušení: část se odesílá nebo nic nečeká |
| 413 | payload_too_large | tělo nad 4 096 bajtů |
| 415 | unsupported_media_type | tělo není application/json |
| 422 | invalid_number, number_not_allowed, invalid_text, text_too_long, not_gsm7, idempotency_conflict | požadavek je správně utvořený, ale nedá se odeslat |
| 429 | rate_limited | příliš mnoho neplatných tokenů (globálně) – počkat Retry-After |
| 429 | limit_exceeded | limit odesílání – počkat Retry-After nebo zvýšit limit |
| 503 | busy, timeout, queue_full, not_ready, maintenance, storage_error, low_memory | všechny úlohy (joby) jsou obsazené, úložiště nezahájilo úlohu do 5 s (nic se nezapsalo), fronta je plná (150), úložiště se po startu obnovuje, probíhá nahrávání firmwaru, chyba úložiště, málo paměti – opakovat po Retry-After |
Každá odpověď 429 a 503 nese Retry-After (sekundy). POST /sms opakujte jen se stejným Idempotency-Key.
5. REST API
JSON over HTTP under the prefix /api/v1. The full reference of every endpoint, field and error code is the file docs/openapi.yaml (OpenAPI 3.1) that comes with the firmware's source code; this chapter summarises it. The API is never served to clients of the gateway's access point.
Authentication and scopes
A token (sgw_ + 32 hex digits, 128 random bits) is created on the API keys page and shown once. Send it with every request:
Authorization: Bearer sgw_0123456789abcdef0123456789abcdef
| Scope | Allows |
|---|---|
send | POST /sms, POST /sms/{id}/cancel |
read | GET /status, /sms, /sms/active, /sms/{id}, /inbox, /inbox/{id}, POST /inbox/ack |
admin | everything |
- A revoked key is refused at once. A lost token cannot be shown again: revoke the key and create a new one.
key_idof a message is the key's slot (0–3); a slot is reused after a revocation.- Requests without a valid token get 401 and share one global budget (10 in a burst, then one every 2 s); beyond it 429 with
Retry-After. A request with a valid token never waits for this budget. - Per-key sending limits (parts per hour / day) are set at the key; the global ones on the Cost protection page.
- New TCP connections are limited to 40 a second in all and 30 a second from one address (bursts of 80 / 60); a connection over the limit is reset at once. Clients behind one proxy share its limit.
Endpoints
Paths are relative to /api/v1 (e.g. GET /api/v1/healthz).
| Method and path | Scope | Purpose |
|---|---|---|
GET /healthz | none | 200 {"status":"ok"} while the message store works; 503 while it is rebuilt after a start or on a storage error. The modem is not part of it. |
GET /status | read | firmware, api_version, instance_id, clock, modem, queues, storage, alarms, webhook and e-mail state, heap, counters |
POST /sms | send | queue a message (202 only after it is stored durably) |
GET /sms | read | the sent log in archive order; cursor (= next_cursor of the previous page), limit, ref; from / to = a time window on the message's creation time (ISO-8601 with Z or an offset, or a date = 00:00 UTC; from inclusive, to exclusive) |
GET /sms/active | read | the queue and the parts waiting for reports |
GET /sms/{id} | read | one outgoing message with all its parts |
POST /sms/{id}/cancel | send | cancel the parts still queued |
GET /inbox | read | received messages, oldest first, by id; since_id, limit, unacked=1 |
GET /inbox/{id} | read | one received message; raw=1 returns the stored TPDUs (hex) instead of the text |
POST /inbox/ack | read | acknowledge received messages ({"ids":[...]}, at most 50) |
Paging: limit 1–50 (default 20), a page is at most 8 kB – it can end earlier with has_more: true.
Sending a message
curl -si http://gateway.example.com/api/v1/sms \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: order-4711-sms" \
-d '{"to":"+420600000001","text":"Your order 4711 is ready.","report":true,"ref":"order-4711"}'
HTTP/1.1 202 Accepted
{"id":1234,"status":"queued","parts":1,"encoding":"gsm7"}
| Field | Meaning |
|---|---|
to | an international number (+ or 00, 8–15 digits; spaces, -, ., (, ) are removed). National and short numbers are not sent. |
text | UTF-8. At most 10 parts: 1,530 GSM-7 septets (an extension character such as € [ ] { } ~ ^ \ | takes two) or 670 UCS-2 units. Longer: 422 text_too_long. |
encoding | auto (default: GSM-7 when possible, else UCS-2), gsm7, ucs2 |
report | ask for delivery reports (default false) |
validity | seconds 60–259,200, default 86,400 (24 h): how long the network tries to deliver |
ttl | seconds 60–259,200, default 3,600 (1 h): parts not sent by then expire |
priority | high or normal (default) |
ref | the client's own reference (at most 64 bytes), a filter of the sent log |
- 202 means stored: the message and its queue record are on flash before the answer; a power cut after a 202 never loses it. A 4xx / 5xx answer means nothing was queued.
encoding: "gsm7"with a text GSM-7 cannot write: 422not_gsm7.- Unknown fields, a field given twice, wrong types: 400. The body is at most 4,096 bytes (413) and must be
Content-Type: application/json(415). - The modem may be down (no network, no SIM): the message is queued all the same and waits;
/statusshows the modem state.
Idempotency – retry without duplicates
- Send an
Idempotency-Keyheader (1–64 printable ASCII characters, unique per message, e.g. an order id) with everyPOST /sms. - The same key with the same request within 24 hours returns the original 202 answer with the header
Idempotent-Replayed: true; nothing new is queued. The same key with a different request: 422idempotency_conflict. - Keys belong to the API key that used them. Requests are compared after normalisation (number notation, field order, defaults). The gateway remembers the last 500 keyed messages.
- The gateway never sends a message in state
unknownagain. To try again, send a new request with a new key – and only when a duplicate is acceptable.
Message states
status | Final | Meaning |
|---|---|---|
canceled | yes | cancelled before anything was sent |
sending | no | a part is being sent, or some parts are sent and others still queued |
queued | no | nothing sent yet, waiting |
unknown | yes | nothing confirmed sent and a part's outcome is unknown – it may or may not have been sent; never sent again |
failed / expired | yes | nothing sent: the network refused it permanently / the ttl passed |
partially_sent | yes | some parts sent, the rest not |
undelivered | yes | all parts sent, a report says a part could not be delivered |
delivered | yes | all parts sent and delivered |
sent | yes / no | all parts sent; final without report, or once the report deadline passed |
A message has, among others, id, to, status, final, created_at (null without a valid clock), key_id (the key slot, null for the gateway's own messages and the Send test SMS page), ref and the array parts. Per part: state (queued, sending, sent, failed, expired, unknown, skipped, canceled), attempts, mr (the network's reference), sent_at, report (none, awaiting, delivered, pending, failed, dropped), report_status and error_code. After a storage damage alarm (storage.corrupt / storage.state_lost) the gateway marks every part that was not final as unknown – it can then also mean "never sent"; it never means "sent twice".
POST /sms/{id}/cancel returns 200 {"id":…, "status":"canceled"|"partially_sent", "canceled_parts":n}; 409 while a part is being sent or when nothing is queued any more.
Receiving: poll the inbox, then acknowledge
since = <last id you processed, 0 at the start>
loop:
page = GET /api/v1/inbox?since_id={since}&limit=50
for m in page.messages: # oldest first
process(m) # idempotently: delivery is at least once
ack.append(m.id)
POST /api/v1/inbox/ack {"ids": ack} # at most 50 per call
since = page.next_since_id
if not page.has_more: sleep(poll interval)
- Persist
sinceonly after the acknowledgement succeeded; after a crash you may see a message again – deduplicate byinstance_id+id. - A simpler alternative:
GET /inbox?unacked=1lists only the messages not acknowledged yet. - Acknowledging an id that no longer exists is ignored. Answer:
{"acked": n}(messages that were not acknowledged before). - A message has
from,received_at(the gateway's clock, UTC),scts(the network's time stamp with the sender's offset),time_valid,encoding,parts,total(the parts a multi-part sender announced),complete,ackedandtext(ordatafor a binary message).
{"messages":[{"id":1201,"from":"+420600000002","received_at":"2026-11-24T12:00:58Z",
"time_valid":true,"scts":"2026-11-24T13:00:55+01:00","encoding":"gsm7",
"parts":1,"complete":true,"acked":false,"text":"Hello"}],
"has_more":false,"next_since_id":1201}
Error codes
Every error is {"error":{"code":"...","message":"..."}}. Program against code (stable); message is for people.
| HTTP | code | When / what to do |
|---|---|---|
| 400 | invalid_json, invalid_request, invalid_parameter, invalid_cursor, invalid_idempotency_key | invalid JSON, a missing / unknown field, a bad parameter, a foreign cursor, a bad header |
| 401 | unauthorized | no / unknown / revoked token |
| 403 | forbidden | the key lacks the scope, or the client is on the gateway's access point |
| 404 | not_found | no such message (or removed by retention) |
| 405 | method_not_allowed | see the Allow header |
| 409 | conflict | cancel: a part is being sent, or nothing is queued any more |
| 413 | payload_too_large | body over 4,096 bytes |
| 415 | unsupported_media_type | a body that is not application/json |
| 422 | invalid_number, number_not_allowed, invalid_text, text_too_long, not_gsm7, idempotency_conflict | the request is well-formed but cannot be sent |
| 429 | rate_limited | too many invalid tokens (global) – wait Retry-After |
| 429 | limit_exceeded | a sending limit – wait Retry-After or raise the limit |
| 503 | busy, timeout, queue_full, not_ready, maintenance, storage_error, low_memory | the jobs are in use, the store did not start the job within 5 s (nothing was written), the queue is full (150), rebuilding after a start, a firmware upload is running, a storage error, low memory – retry after Retry-After |
Every 429 and 503 carries Retry-After (seconds). Retry POST /sms only with the same Idempotency-Key.
6. Webhook a e-mailová upozornění
Webhook je kanál „push“ vedle API, ne jeho náhrada: potvrzování schránky zůstává výslovné a úplná data jsou vždy v API. Oba kanály se nastavují na stránce Notifications a jejich nastavení je uloženo na oddílu úložiště.
Typy událostí
| Událost | Obsah data |
|---|---|
sms.received | objekt jako v GET /inbox/{id} |
sms.status | objekt jako v GET /sms/{id} bez textu; stav v okamžiku doručení události |
modem.down, modem.up, sim.error | modem (stav, can_send, SIM, operátor); modem.down se pošle, když modem 60 s nemůže odesílat (pokud od startu ještě neběžel, po 5 minutách); vypnutý modem ani nahrávání firmwaru se za výpadek nepovažují |
storage.full | reason (partition = oddíl zaplněn aspoň z 90 %, write_error), partition_used_pct, storage_error |
storage.modem_full | modem_storage obsazeno / celkem |
queue.full | outbox, capacity |
heartbeat, test | uptime_s, backlog, modem; event_id 0, nikdy se neopakují |
Zpráva, kterou úložiště už nemá, přijde jako {"id": n, "evicted": true}.
Nastavení webhooku
- Enabled
- Zapíná kanál; ve výchozím stavu vypnuto. Zapnout jde jen s platným secret.
- URL
https://host[:port]/cestanebohttp://…(jméno hostitele nebo IPv4, ne IPv6), nejvýš 160 znaků. Jméno a heslo v URL (user:heslo@) se odmítnou – k ověření slouží secret nebo vlastní hlavička. Přesměrování se nesledují (3xx = neúspěch); jenPOST.- TLS verification
- viz Režimy TLS níže.
- Extra request headers
- Nejvýš 4 hlavičky, celkem 256 bajtů (jméno do 32 znaků, hodnota do 128), např.
Authorization. Hodnoty se už nikdy nezobrazí ani nezapíší do logu; prázdná hodnota ponechá uloženou (jen pro stejné jméno a stejný cíl – po změně schématu, hostitele nebo portu URL se musí zadat znovu). Hlavičky, které nastavuje brána nebo které mění rámování (Host,Content-Length,Content-Type,X-Signature,X-Timestamp…), se odmítnou. Pověření shttp://stránka označí varováním. - Události
sms.received,sms.status, systémové. Výchozí: všechny.- Heartbeat
- Každých N minut (0 = vypnuto, nejvýš 1 440), pokud mezitím nic jiného nebylo doručeno.
- Secret
- 16–64 tisknutelných znaků ASCII bez mezer. Generate a new secret vytvoří
whsec_+ 40 hex číslic a zobrazí ho jednou. Prázdné pole ponechá uložený. - Send a test event
- Pošle událost typu
testa ukáže výsledek.
Požadavek a podpis
POST /hook HTTP/1.1
Host: receiver.example.com
User-Agent: sms-gateway/1.0.0
Content-Type: application/json
Content-Length: …
X-Timestamp: 1795521660
X-Signature: 3f0c…e9 (64 hex číslic)
Connection: close
{"gateway":{"instance_id":"0123456789abcdef","firmware":"1.0.0"},
"sent_at":"2026-11-24T12:01:00Z","time_valid":true,
"events":[{"event_id":57,"type":"sms.received","occurred_at":"2026-11-24T12:00:58Z",
"data":{"id":1201,"from":"+420600000002", … ,"text":"Dobrý den"}}]}
- Nejvýš 20 událostí a 4 kB v jednom požadavku. Jedna větší událost přijde sama se zkráceným textem a
"truncated": true; celou zprávu přečtěte přesGET /inbox/{id}. X-Signature= HMAC-SHA256 s klíčem secret nadX-Timestamp+"."+ surové tělo, malými hex číslicemi. Porovnávejte v konstantním čase a odmítejte stará časová razítka. Bez platného času posílá bránaX-Timestamp: 0aX-Time-Valid: false; proti opakování pak chrání jenevent_id. Vlastní hlavičky do podpisu nepatří.
import hashlib, hmac, time
def verify(secret: bytes, headers, body: bytes, max_age=300) -> bool:
ts = headers.get("X-Timestamp", "")
sig = headers.get("X-Signature", "")
want = hmac.new(secret, ts.encode() + b"." + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(want, sig):
return False
if headers.get("X-Time-Valid") == "false":
return True # brána bez času: spolehnout se na event_id
return abs(time.time() - int(ts)) <= max_age
Režimy TLS
| Režim | Ověření |
|---|---|
| Certificate bundle (výchozí) | řetězec musí končit u jedné z asi 200 veřejných CA vestavěných ve firmwaru a certifikát musí obsahovat hostitele z URL (DNS jméno, u IP adresy iPAddress subjectAltName) |
| Own CA | nahraná CA (PEM, kořen a nejvýš jeden mezilehlý certifikát, nejvýš 4 096 bajtů; zkontroluje se při nahrání); jméno hostitele se kontroluje |
| Certificate fingerprint (pinning) | SHA-256 certifikátu serveru přes celé DER (to, co vypíše openssl x509 -noout -fingerprint -sha256; s dvojtečkami i bez). Řetězec, jméno ani data se nekontrolují; při obnově certifikátu se musí otisk aktualizovat. |
| INSECURE | žádné ověření – jen při výslovné volbě; stránka ho ukáže červeně, /status hlásí tls_verify: "insecure" a alarm notify.tls_insecure |
- TLS 1.2, SNI (u IP adresy se SNI neposílá), certifikáty RSA i ECDSA. Neúspěšné ověření = neúspěšné doručení; brána nikdy nepřejde z ověřeného režimu na nezabezpečený ani na HTTP.
- Pravidlo hodin: režimy bundle a own CA kontrolují platnost certifikátů, a proto čekají na platný čas (NTP). Do té doby je kanál „held“, nic se nepočítá jako chyba a události čekají. Režimy fingerprint a insecure čas nepotřebují.
- Najednou běží jedno TLS spojení (webhook a e-mail se střídají) a jen pokud je dost paměti (spojení zabere asi 46 kB a začne jen při zhruba 54 kB volné paměti); jinak doručení počká („held: low memory for TLS“).
- HTTP: tělo je podepsané, ale nešifrované – jen ve stejné izolované síti nebo k reverzní proxy v ní.
Doručení, opakování a fronta
- Každá odpověď 2xx znamená doručeno. Cokoli jiného (jiný stav, žádná odpověď do 10 s, odmítnuté spojení) se opakuje s exponenciálním odstupem: 10 s, 20 s, … nejvýš 15 minut mezi pokusy. Od dávky, která selhává 24 hodin, brána upustí (
given_up). - Deduplikujte podle
gateway.instance_id+event_id: ztracená odpověď nebo restart hned po doručení pošle stejné události znovu. Události mohou přijít v jiném pořadí než data v API. - Webhook nikdy nepotvrzuje schránku – dál používejte
POST /inbox/ack. - Fronta pojme 256 událostí a přežije restart. Když je plná, nejstarší události se zahodí (i
sms.received– zprávy zůstanou ve schránce; po výpadku si je vyzvedněte z API); počítá se jakodropped. - Jméno hostitele v URL překládá DNS klient brány, který může čekat desítky sekund, když DNS server neodpovídá (čekají jen upozornění). Doporučujeme IP adresu.
- Během běhu přístupového bodu a při nedostatku paměti (pod asi 20 kB) upozornění čekají („held: …“); nic se neztratí ani nepočítá jako chyba.
- Enabled
- Zapíná kanál; ve výchozím stavu vypnuto.
- Server a zabezpečení
- Jméno nebo IP adresa, port (výchozí 587) a zabezpečení: STARTTLS (výchozí; server, který ho nenabídne, je chyba – nikdy se nepokračuje bez TLS), SMTPS (TLS od prvního bajtu, obvykle 465) nebo Plain SMTP k internímu relay (s varováním). Ověření TLS stejně jako u webhooku (bundle, own CA, fingerprint, insecure) včetně pravidla hodin.
- AUTH
- Volitelně jméno a heslo (PLAIN nebo LOGIN podle nabídky serveru po TLS). Heslo se na stránce nezobrazuje; prázdné pole ho ponechá, volba Clear the password ho smaže. Bez TLS by heslo šlo čitelně: vyžaduje volbu Allow AUTH without TLS (výchozí vypnuto).
- EHLO, From, příjemci
- EHLO jméno, adresa odesílatele, nejvýš 4 příjemci.
- Události
- Výchozí: přijaté zprávy a systémové události (změny stavu odeslaných zpráv lze zapnout).
- Předmět
- Šablona s
{event},{from},{id},{gateway}; výchozí[SMS gateway] {event} {from}. - Mails per hour
- Nejvýš N e-mailů za hodinu (výchozí 30, 0 = bez limitu). Je to omezení četnosti, ne zpoždění: události nad limit se nepošlou (
skipped); další e-mail uvede jejich počet; když po otevření okna není co poslat, přijde jeden souhrnný e-mail. Webhook to neovlivní. - Obsah
- Include the SMS text (výchozí ano), The sender's full number (výchozí ano; jinak maskované). Jeden e-mail na událost, UTF-8, hlavičky
X-SMS-Gateway-Event,X-SMS-Gateway-Event-Id,Auto-Submitted: auto-generated, bez odkazů. - Send a test e-mail
- Pošle zkušební e-mail a ukáže výsledek.
Odpovědi 4xx a chyby spojení se opakují s odstupem (jako u webhooku se po 24 h od doručení upustí). 5xx před příjemci (pozdrav, EHLO, AUTH – např. špatné heslo –, MAIL FROM) je problém kanálu: opakuje se také a události čekají. Po 5xx pro samotný e-mail se od něj hned upustí; odmítnutý příjemce se přeskočí.
Stav v /status
Objekty webhook a smtp: enabled, state (idle, sending, retrying in N s, no network, disabled, held: …), backlog, delivered / failed / given_up od startu, dropped, skipped (e-mail), last_status, last_error, last_success, retry_in_s, transport a tls_verify.
6. Webhook and e-mail notifications
The webhook is a push channel next to the API, not a replacement: the inbox acknowledgement stays explicit and the full data is always in the API. Both channels are set on the Notifications page; their settings are kept on the storage partition.
Event types
| Event | data |
|---|---|
sms.received | the object of GET /inbox/{id} |
sms.status | the object of GET /sms/{id} without the text; the state at the moment of the delivery |
modem.down, modem.up, sim.error | modem (state, can_send, SIM, operator); modem.down is sent when the modem cannot send for 60 s (after 5 minutes if it has not been up since the start); a modem switched off or a firmware upload is not an outage |
storage.full | reason (partition = the partition at least 90 % used, write_error), partition_used_pct, storage_error |
storage.modem_full | modem_storage used / total |
queue.full | outbox, capacity |
heartbeat, test | uptime_s, backlog, modem; event_id 0, never retried |
A message the storage no longer holds comes as {"id": n, "evicted": true}.
Webhook settings
- Enabled
- Switches the channel on; off by default. It can be switched on only with a valid secret.
- URL
https://host[:port]/pathorhttp://…(host name or IPv4, not IPv6), at most 160 characters. A user name and password in the URL (user:password@) are refused – use the secret or an extra header. Redirects are not followed (3xx = failure);POSTonly.- TLS verification
- see TLS modes below.
- Extra request headers
- At most 4 headers, 256 bytes in all (a name of up to 32 characters, a value of up to 128), e.g.
Authorization. Values are never shown again nor logged; an empty value keeps the stored one (only for the same name and the same receiver – after a change of the URL's scheme, host or port it must be entered again). Headers the gateway sets or that change the framing (Host,Content-Length,Content-Type,X-Signature,X-Timestamp…) are refused. A credential withhttp://is warned about on the page. - Events
sms.received,sms.status, system. Default: all.- Heartbeat
- Every N minutes (0 = off, at most 1,440) while nothing else was delivered.
- Secret
- 16–64 printable ASCII characters without spaces. Generate a new secret makes
whsec_+ 40 hex digits and shows it once. An empty field keeps the stored one. - Send a test event
- Sends an event of type
testand shows the result.
Request and signature
POST /hook HTTP/1.1
Host: receiver.example.com
User-Agent: sms-gateway/1.0.0
Content-Type: application/json
Content-Length: …
X-Timestamp: 1795521660
X-Signature: 3f0c…e9 (64 hex digits)
Connection: close
{"gateway":{"instance_id":"0123456789abcdef","firmware":"1.0.0"},
"sent_at":"2026-11-24T12:01:00Z","time_valid":true,
"events":[{"event_id":57,"type":"sms.received","occurred_at":"2026-11-24T12:00:58Z",
"data":{"id":1201,"from":"+420600000002", … ,"text":"Hello"}}]}
- At most 20 events and 4 kB per request. A single larger event comes alone with its text cut and
"truncated": true; read the full message withGET /inbox/{id}. X-Signature= lower-case hex HMAC-SHA256, keyed with the secret, overX-Timestamp+"."+ the raw body. Compare in constant time and reject old timestamps. Without a valid clock the gateway sendsX-Timestamp: 0andX-Time-Valid: false; then onlyevent_idprotects against a replay. Extra headers are not part of the signature.
import hashlib, hmac, time
def verify(secret: bytes, headers, body: bytes, max_age=300) -> bool:
ts = headers.get("X-Timestamp", "")
sig = headers.get("X-Signature", "")
want = hmac.new(secret, ts.encode() + b"." + body, hashlib.sha256).hexdigest()
if not hmac.compare_digest(want, sig):
return False
if headers.get("X-Time-Valid") == "false":
return True # no clock on the gateway: rely on event_id
return abs(time.time() - int(ts)) <= max_age
TLS modes
| Mode | Verification |
|---|---|
| Certificate bundle (default) | the chain must end at one of about 200 public CAs built into the firmware, and the certificate must name the URL's host (DNS name; for an IP address an iPAddress subjectAltName) |
| Own CA | an uploaded CA (PEM, a root and at most one intermediate, at most 4,096 bytes; checked when uploaded); the host name is checked |
| Certificate fingerprint (pinning) | the SHA-256 of the server's certificate over its whole DER (what openssl x509 -noout -fingerprint -sha256 prints; with or without colons). The chain, host name and dates are not checked; the fingerprint must be updated when the certificate is renewed. |
| INSECURE | no verification at all – only when chosen explicitly; the page shows it in red, /status reports tls_verify: "insecure" and the alarm notify.tls_insecure |
- TLS 1.2, SNI (not sent for an IP address), RSA and ECDSA certificates. A failed verification is a failed delivery; the gateway never falls back from a verified mode to insecure, nor to HTTP.
- Clock rule: the bundle and own-CA modes check the certificates' validity dates and so wait for a valid clock (NTP). Until then the channel is "held", nothing counts as failed and the events wait. The fingerprint and insecure modes do not need the clock.
- One TLS session at a time (the webhook and the e-mail take turns), and only when there is enough memory (a session takes about 46 kB and starts only with about 54 kB free); otherwise the delivery waits ("held: low memory for TLS").
- HTTP: the body is signed but not encrypted – only in the same isolated network, or to a reverse proxy there.
Delivery, retries and the queue
- Any 2xx answer means delivered. Anything else (another status, no answer within 10 s, a refused connection) is retried with exponential backoff: 10 s, 20 s, … at most 15 minutes between attempts. A batch that keeps failing for 24 hours is given up (
given_up). - Deduplicate by
gateway.instance_id+event_id: a lost answer or a restart right after a delivery sends the same events again. Events may arrive out of order relative to the API. - The webhook never acknowledges the inbox – keep using
POST /inbox/ack. - The queue holds 256 events and survives restarts. When it is full the oldest events are dropped (also
sms.received– the messages stay in the inbox; poll the API after an outage); counted asdropped. - A host name in the URL is resolved by the gateway's DNS client, which can wait tens of seconds when the DNS server does not answer (only the notifications wait). Prefer an IP address.
- While the access point runs and while memory is low (under about 20 kB), notifications wait ("held: …"); nothing is lost or counted as failed.
- Enabled
- Switches the channel on; off by default.
- Server and security
- Host name or IP address, port (default 587) and security: STARTTLS (default; a server that does not offer it is a failure – never continued without TLS), SMTPS (TLS from the first byte, usually 465) or Plain SMTP to an internal relay (with a warning). TLS verification as for the webhook (bundle, own CA, fingerprint, insecure), including the clock rule.
- AUTH
- Optionally a user name and password (PLAIN or LOGIN, as the server offers after TLS). The password is never shown on the page; an empty field keeps it, Clear the password removes it. Without TLS the password would travel readable: that needs Allow AUTH without TLS (off by default).
- EHLO, From, recipients
- The EHLO name, the From address, at most 4 recipients.
- Events
- Default: received messages and system events (status changes of sent messages can be switched on).
- Subject
- A template with
{event},{from},{id},{gateway}; default[SMS gateway] {event} {from}. - Mails per hour
- At most N mails an hour (default 30, 0 = no limit). A rate limit, not a delay: events over it are not mailed (
skipped); the next mail says how many; when the window reopens with nothing else to send, one summary mail goes out. The webhook is not affected. - Content
- Include the SMS text (default on), The sender's full number (default on; else masked). One mail per event, UTF-8, headers
X-SMS-Gateway-Event,X-SMS-Gateway-Event-Id,Auto-Submitted: auto-generated, no links. - Send a test e-mail
- Sends a test mail and shows the result.
4xx replies and connection errors are retried with backoff (as the webhook, given up after 24 h). A 5xx before the recipients (greeting, EHLO, AUTH – e.g. a wrong password –, MAIL FROM) is a problem of the channel: retried as well, the events wait. A 5xx for the mail itself gives that mail up at once; a refused recipient is skipped.
State in /status
The objects webhook and smtp: enabled, state (idle, sending, retrying in N s, no network, disabled, held: …), backlog, delivered / failed / given_up since boot, dropped, skipped (e-mail), last_status, last_error, last_success, retry_in_s, transport and tls_verify.
7. Aktualizace firmwaru
Firmware se aktualizuje jen nahráním souboru .bin na stránce Firmware. Žádné stahování z URL ani automatické aktualizace. Během nahrávání brána přejde do režimu údržby: modem nezačíná nové odesílání, příchozí zprávy zůstávají v modemu a POST /sms odpovídá 503 maintenance; potom se pokračuje.
Druhy obrazů
| Obraz | Co se stane |
|---|---|
| Podepsaný klíčem z firmwaru, stejná nebo vyšší verze | nainstaluje se hned a brána se restartuje |
| Podepsaný, ale starší verze | čeká na potvrzení správcem 10 minut, jen v relaci, která ho nahrála – i při zapnuté volbě Signed images only |
| Nepodepsaný, nebo podepsaný neznámým klíčem (obraz tohoto firmwaru) | čeká na potvrzení 10 minut, jen v relaci, která ho nahrála; s volbou Signed images only se odmítne |
| Cizí obraz (jiný produkt, jiná deska, poškozený podpisový blok, neplatný podpis známým klíčem, zkrácený soubor) | odmítne se; první sektor slotu se smaže, takže odmítnutý obraz nikdy nenastartuje |
Potvrzení platí přesně pro nahraný obraz (jeho SHA-256 a délku). Obraz, který zůstal čekat přes restart, se při startu smaže.
Ověření a návrat
- Nový firmware se ponechá, jakmile 120 s běží bez problému (běžící hlavní smyčka, webový server, zdravé síťové vlákno); po každém zakolísání stavu se 120 s počítá znovu. Stránka Firmware ukazuje zbývající čas.
- Jakýkoli reset, pád nebo výpadek napájení před tím vrátí předchozí firmware; návrat se zapíše do logu.
- Restart, o který požádáte (webové rozhraní nebo
reset-networkna sériové konzoli), nový firmware nikdy neoznačí jako platný: počká na ověření a teprve pak bránu restartuje. Když se obraz do 180 s od první žádosti o restart neověří, restartuje se neověřený a zavaděč spustí předchozí firmware; další žádosti tuto lhůtu neposouvají. Výsledná stránka se obnoví až po skutečném čekání. - Když se označení firmwaru jako platného nepovede (ani po opakovaných pokusech), požadovaný restart proběhne hned a vrátí předchozí firmware; stránka Firmware i výsledné stránky to uvádějí.
- Automatické restarty kvůli špatnému stavu (hlídání fragmentace paměti, watchdog) nečekají.
- Dokud ověření běžícího obrazu neskončí, brána nepřijme nové nahrání ani potvrzení čekajícího obrazu (po nepovedeném označení až po restartu).
Doporučení: zapněte Signed images only, pokud nepotřebujete instalovat vlastní sestavení. Pak se nepodepsané obrazy a obrazy s neznámým klíčem odmítnou; starší podepsaná verze se nainstaluje jen s vaším potvrzením.
7. Firmware updates
The firmware is updated only by uploading a .bin file on the Firmware page. No download from a URL and no automatic updates. During the upload the gateway is in maintenance mode: the modem starts no new sends, received messages stay in the modem and POST /sms answers 503 maintenance; afterwards it continues.
Kinds of images
| Image | What happens |
|---|---|
| Signed with a key of the firmware, the same or a higher version | installed at once, the gateway restarts |
| Signed, but an older version | waits for the admin's confirmation for 10 minutes, only in the session that uploaded it – also while Signed images only is on |
| Unsigned, or signed with an unknown key (an image of this firmware) | waits for the confirmation for 10 minutes, only in the session that uploaded it; refused while Signed images only is on |
| A foreign image (another product, another board, a malformed signature block, a bad signature with a known key, a truncated file) | refused; the slot's first sector is erased so a refused image can never boot |
A confirmation applies to exactly the uploaded image (its SHA-256 and length). An image left waiting across a restart is erased at the next start.
Validation and rollback
- A new firmware is kept once it has run 120 s of normal operation (the main loop running, the web server up, the network thread healthy); any health dip starts the 120 s again. The Firmware page shows the time left.
- Any reset, crash or power cut before that returns to the previous firmware; the rollback is written to the log.
- A restart you ask for (the web interface, or
reset-networkon the serial console) never marks the new firmware valid: it waits for the validation and only then restarts. When the image is not validated within 180 s of the first restart request, it restarts unvalidated and the bootloader starts the previous firmware; further requests do not move that time. The result page reloads only after the real wait. - When marking the firmware valid fails (also after the retries), a requested restart goes ahead at once and returns to the previous firmware; the Firmware page and the result pages say so.
- Automatic restarts for bad health (the heap-fragmentation watch, the watchdog) never wait.
- Until the validation of the running image is done, the gateway takes no new upload and no confirmation of a waiting image (after a failed marking: not until the restart).
Recommendation: switch Signed images only on unless you need to install your own builds. Unsigned images and images with an unknown key are then refused; an older signed version is installed only with your confirmation.
8. Spolehlivost
Výpadek napájení a konzistence úložiště
- 202 znamená uloženo: zpráva k odeslání je na flash dřív, než API odpoví.
- Příjem: zpráva se z modemu smaže až po trvalém uložení; po výpadku ji modem nabídne znovu a deduplikace zabrání druhé kopii.
- Odesílání: stav
sendingse zapíše před předáním části modemu. Výpadek během odesílání nechá část ve stavuunknown, který se nikdy automaticky neopakuje – výpadek nikdy nezpůsobí duplicitní SMS. - Úložiště používá neměnné soubory, záznamy připojované na konec s kontrolním bodem a přepisy na místě jen u malých souborů. Po startu se úložiště sestaví znovu (obvykle do 2 s), neúplné záznamy se zahodí a stav se srovná; mezitím API odpovídá 503
not_ready. - Když se při startu najdou poškozená data, zvedne se alarm (
storage.corrupt,storage.state_lost); zbytek dat zůstává.
Obnova Ethernetu
Ethernetový PHY (LAN8720A) může po výpadku linku hlásit navázaný link, kterým nic neprojde. Brána proto sleduje příjem rámců od jiných stanic a v těchto případech resetuje PHY (zastavení ovladače, reset PHY, nový start; při chybě ještě jednou):
- link je nahoře, ale 30 s nepřišel žádný rámec od jiné stanice a výpadek má znaky „falešného“ linku (link do 5 s po výpadku nebo ozvěna vlastních rámců), jinak po 65 s ticha;
- se statickou adresou až poté, co výchozí brána sítě aspoň jednou odpověděla na ARP, jinak po 10 minutách úplného ticha;
- s DHCP: rámce chodí, ale adresa nepřišla ani po 3 minutách;
- po ztrátě linku: link nenaběhne do 30 s.
Prvních 10 resetů zhruba po 30 s, pak se interval zdvojnásobuje až na 10 minut; minuta bez problému sérii ukončí. Deska bez kabelu se neresetuje; výpadek routeru reset PHY nevyvolá, dokud v LAN někdo vysílá.
Logování linku: každá změna linku (up / down) má v logu obvykle vlastní řádek, i během série resetů PHY; výjimečně (reset, při kterém link kmitá déle) se několik změn objeví jen v souhrnném řádku dané minuty. Omezen je jen kmitající link: nejvýš 5 vlastních řádků za libovolnou minutu, pak jeden souhrnný řádek za minutu s počtem změn. Kmitání skončí, jakmile je četnost zpět pod limitem a souhrn byl zapsán, nebo minutou bez změny.
Záložní uplink
- Ethernet má přednost: když má adresu, provoz jde přes něj. Je-li nastavena WiFi stanice a Ethernet adresu nemá, provoz přejde na WiFi. Výchozí trasa a DNS servery se nastavují podle aktivního rozhraní (kontrola každé 2 s).
- S nastaveným heslem správce se při výpadku linku nikdy nespustí přístupový bod. LTE není datový uplink.
- Příjem a odesílání SMS na síti LAN nezávisí: během výpadku LAN se zprávy dál přijímají a odesílají z fronty; webhook a e-mail počkají.
Modem a systém
- Modem se kontroluje každých 30 s (po neúspěšné kontrole za 5 s). Po 3 neúspěšných kontrolách nebo 3 vypršených příkazech za sebou se odpojí od napájení nejméně na 20 s (po opakovaných selháních déle, až 10 minut) a znovu zapne – nikdy uprostřed odesílání.
- Watchdog úloh (10 s) restartuje zaseknutý systém. Když největší volný blok paměti zůstane 15 minut pod 8 kB (fragmentace), brána se řízeně restartuje; nejvýš 3 takové restarty za sebou, čítač se vynuluje po hodině bez problému.
Co ukazuje stránka Status
Alarmy s vysvětlením, příčinu posledního restartu, dobu běhu, zdroj času a napájení, paměť, stav modemu a úložiště, stav upozornění a síť (uplink, link Ethernetu a rychlost, adresa, WiFi, přístupový bod). Podrobné čítače obnovy Ethernetu jsou v diagnostice /diag/heap (viz další kapitola).
8. Reliability
Power loss and store consistency
- 202 means stored: a message to send is on flash before the API answers.
- Receiving: a message is deleted from the modem only after it is stored durably; after a power cut the modem offers it again and the deduplication prevents a second copy.
- Sending: the state
sendingis written before a part goes to the modem. A power cut during a send leaves the partunknown, which is never retried automatically – a power cut never causes a duplicate SMS. - The store uses immutable files, append-only records with a checkpoint, and in-place rewrites only for small files. After a start the store is rebuilt (usually within 2 s), incomplete records are discarded and the state reconciled; meanwhile the API answers 503
not_ready. - When damaged data is found at a start, an alarm is raised (
storage.corrupt,storage.state_lost); the rest of the data stays.
Ethernet recovery
The Ethernet PHY (LAN8720A) can report an established link after a link loss through which nothing passes. The gateway therefore watches for frames from other stations and resets the PHY in these cases (driver stop, PHY reset, a new start; once more on an error):
- the link is up but no frame from another station arrived for 30 s and the loss has the signature of a phantom link (a link-up within 5 s of the loss, or echoes of its own frames), otherwise after 65 s of silence;
- with a static address only after the network's gateway has answered ARP at least once, otherwise after 10 minutes of total silence;
- with DHCP: frames arrive but no address came after 3 minutes;
- after a lost link: the link does not come back within 30 s.
The first 10 resets come about 30 s apart, then the interval doubles up to 10 minutes; one healthy minute ends the series. A board without a cable is not reset; a router outage does not trigger a PHY reset while someone in the LAN is transmitting.
Link logging: every link change (up / down) normally has its own log line, also during a series of PHY resets; occasionally (a reset during which the link bounces longer) a few changes are reported only in that minute's summary line. Only a flapping link is limited: at most 5 own lines in any minute, then one summary line a minute with the number of changes. The flapping ends as soon as the rate is back under the limit and its summary is out, or after a minute without a change.
Uplink failover
- Ethernet comes first: while it has an address, traffic goes over it. With a WiFi station configured and no Ethernet address, traffic moves to WiFi. The default route and the DNS servers follow the active interface (checked every 2 s).
- With an admin password set, a link loss never starts an access point. LTE is not a data uplink.
- SMS receiving and sending do not depend on the LAN: during a LAN outage messages are still received and sent from the queue; the webhook and e-mail wait.
Modem and system
- The modem is checked every 30 s (5 s after a failed check). After 3 failed checks or 3 command timeouts in a row its supply is cut for at least 20 s (longer after repeated failures, up to 10 minutes) and switched on again – never in the middle of a send.
- The task watchdog (10 s) restarts a stuck system. When the largest free memory block stays under 8 kB for 15 minutes (fragmentation), the gateway restarts in a controlled way; at most 3 such restarts in a row, the counter clears after an hour without the problem.
What the Status page shows
Alarms with explanations, the reason for the last restart, uptime, the time and power sources, memory, the modem and store state, the notification channels and the network (uplink, Ethernet link and speed, address, WiFi, access point). The detailed Ethernet recovery counters are in the /diag/heap diagnostics (next chapter).
9. Diagnostika a řešení problémů
Logy
Stránka Logs (filtr úrovně, automatické obnovení). Log je v RAM a restart ho smaže; před restartem, který chcete zkoumat, si ho uložte. Stejné řádky vypisuje sériová konzole.
Sériová konzole
115 200 Bd, 8N1, přes USB konektor desky (převodník USB-UART). Vyžaduje fyzický přístup. Příkaz zakončete Enterem:
| Příkaz | Účinek |
|---|---|
reset-password | smaže heslo správce webového rozhraní; přihlaste se prázdným heslem a nastavte nové |
reset-network | Ethernet zpět na DHCP, WiFi vypnout, restart (při ověřování nového firmwaru počká, viz kapitola 7) |
Po reset-password je brána bez hesla: přihlásí se kdokoli, kdo se k webovému rozhraní dostane, a bez linku Ethernetu a bez připojené WiFi stanice se po 10 s spustí otevřený přístupový bod pro nastavení. Nové heslo nastavte hned. Žádný z příkazů nemaže zprávy ani klíče; reset-network jen přepne Ethernet na DHCP a vypne WiFi. Funkce pro obnovení továrního stavu v rozhraní není.
Diagnostické endpointy
GET /diag/heap, GET /diag/modem a GET /diag/store vrací JSON s podrobnými čítači (paměť a důvod restartu, stav obnovy Ethernetu; stav a čítače modemu; stav úložiště). Vyžadují přihlášenou relaci správce (jinak 401) a slouží pro podporu; jejich obsah se může mezi verzemi měnit. Pro integrace a monitoring používejte /api/v1/healthz a /api/v1/status.
Časté problémy
| Příznak | Příčina a řešení |
|---|---|
| Žádný link Ethernetu | Zkontrolujte kabel a port switche; Status ukáže „no link“. Brána PHY sama resetuje (kapitola 8), každá změna linku je v logu. Bez linku a bez hesla se otevře přístupový bod pro nastavení. |
| Brána nedostupná po změně statické adresy | Zapnutý obnovovací přístupový bod: vypněte a zapněte bránu a připojte se k němu do 5 minut. Jinak reset-network na sériové konzoli. |
| Modem nemůže odesílat, SIM chyba, bez registrace | Status → Modem (stav, SIM, síť, signál). Zkontrolujte SIM, PIN (při odmítnutém PIN zadejte nový na stránce Network), APN, pokrytí. Alarm „SIM has no SMS centre number“: SIM nemá číslo SMS centra – řeší operátor. Zprávy mezitím čekají ve frontě. |
POST /sms vrací 429 limit_exceeded | Dosažený limit; bez platného času se limity nepřetáčejí – zajistěte přístup k NTP. |
POST /sms vrací 422 number_not_allowed | Číslo mimo povolené předvolby nebo zvláštní číslo pod +420 (0xx, 1xx, 700, 8xx, 9xx, krátké); přidejte výjimku na stránce Cost protection (jen pokud je to opravdu žádoucí). |
| Žádná upozornění nechodí | Kanál není zapnutý (Enabled, ve výchozím stavu vypnuto; webhook navíc potřebuje platný secret), nebo nejsou zvolené události. U nezapnutého kanálu ukáže /status state: "disabled". |
| Upozornění selhávají | Notifications → stav kanálu a last_error. „held: waiting for a valid clock“ = čeká se na NTP; ověření TLS (bundle / CA / otisk, jméno hostitele v certifikátu); 3xx se nesledují; dostupnost DNS (raději IP adresa); Send a test event. U e-mailu: server nenabízí STARTTLS, špatné heslo AUTH, AUTH bez TLS není povolen. |
| Úložiště není připojeno | Alarm „The storage partition is not mounted“: nic se neukládá ani neodesílá. Pokud zařízení už data mělo, nejdřív ho jednou restartujte; teprve pak naformátujte na stránce System (formátování smaže vše). |
inbox.evicted | Integrace nepotvrzovala a kvóta nebo stáří vyřadily nepotvrzené zprávy. Nastavte potvrzování (POST /inbox/ack), potom alarm smažte. |
| API vrací 401 / 403 | 401: chybí, je neznámý nebo zneplatněný token (hlavička Authorization: Bearer …). 403: klíč nemá potřebné oprávnění, nebo je klient připojen přes přístupový bod brány. |
| API vrací 503 | Podle code: not_ready – úložiště se po startu obnovuje (sekundy); busy / timeout – souběžná zátěž, opakovat po Retry-After; queue_full – 150 zpráv ve frontě (zkontrolujte na stránce Status, zda modem může odesílat); maintenance – nahrává se firmware; storage_error / low_memory – viz alarmy na stránce Status a log. |
| Hlášení „No valid clock“ | Brána nemá čas z NTP ani z mobilní sítě: limity se nepřetáčejí, ověřené TLS čeká, časy zpráv nejsou známé. Povolte odchozí NTP (UDP 123). |
| Firmware se nenainstaloval | Cizí nebo poškozený obraz (jiný produkt nebo deska, špatný podpis, zkrácený soubor) se odmítne. Nepodepsaný obraz se s volbou Signed images only odmítne, jinak čeká 10 minut na potvrzení – jen v relaci, která ho nahrála; nepotvrzený se zahodí. Starší podepsaná verze čeká na potvrzení také 10 minut (i při Signed images only). Během ověřování právě nainstalovaného firmwaru (120 s) se nové nahrání nepřijme – počkejte. Důvod ukáže výsledná stránka nahrání a log. |
| Po aktualizaci běží předchozí verze | Nový firmware nevydržel 120 s běžného provozu (reset, pád, výpadek napájení, restart, který se do 180 s od první žádosti neověřil, nebo nepovedené označení jako platného) a brána se vrátila k předchozímu (návrat je zapsán v logu). Zkontrolujte, že obraz je pro tuto desku, a zkuste instalaci znovu; při opakování kontaktujte dodavatele. |
| Formuláře za proxy vracejí 403 | Proxy přepisuje hlavičku Host; zachovejte ji (nginx: proxy_set_header Host $host;). |
| Zapomenuté heslo správce | reset-password na sériové konzoli, pak se přihlaste prázdným heslem a nastavte nové. |
9. Diagnostics and troubleshooting
Logs
The Logs page (level filter, auto-refresh). The log is kept in RAM and a restart clears it; save it before a restart you want to investigate. The serial console prints the same lines.
Serial console
115,200 Bd, 8N1, over the board's USB connector (a USB-UART bridge). Needs physical access. End a command with Enter:
| Command | Effect |
|---|---|
reset-password | clears the web admin password; log in with an empty password and set a new one |
reset-network | Ethernet back to DHCP, WiFi off, restart (waits while a new firmware is being validated, see chapter 7) |
After reset-password the gateway has no password: anyone who reaches the web interface can log in, and without an Ethernet link and without a connected WiFi station the open setup access point starts after 10 s. Set the new password at once. Neither command deletes messages or keys; reset-network only switches Ethernet to DHCP and WiFi off. The interface has no factory-reset function.
Diagnostic endpoints
GET /diag/heap, GET /diag/modem and GET /diag/store return JSON with detailed counters (memory and the reset reason, the Ethernet recovery state; the modem state and counters; the store state). They need a logged-in admin session (401 otherwise) and are meant for support; their content may change between versions. For integrations and monitoring use /api/v1/healthz and /api/v1/status.
Common problems
| Symptom | Cause and fix |
|---|---|
| No Ethernet link | Check the cable and the switch port; Status shows "no link". The gateway resets the PHY by itself (chapter 8), every link change is in the log. Without a link and without a password the setup access point opens. |
| Gateway unreachable after a static address change | With the recovery access point on: power-cycle the gateway and join it within 5 minutes. Otherwise reset-network on the serial console. |
| The modem cannot send, SIM error, no registration | Status → Modem (state, SIM, network, signal). Check the SIM, the PIN (after a refused PIN enter a new one on the Network page), the APN, the coverage. Alarm "SIM has no SMS centre number": the SIM lacks the SMS centre number – a matter for the operator. Messages wait in the queue meanwhile. |
POST /sms answers 429 limit_exceeded | A limit is reached; without a valid clock the limits do not roll over – make sure NTP is reachable. |
POST /sms answers 422 number_not_allowed | The number is outside the allowed prefixes or a special number under +420 (0xx, 1xx, 700, 8xx, 9xx, short); add an exception on the Cost protection page (only if really wanted). |
| No notifications at all | The channel is not switched on (Enabled, off by default; the webhook also needs a valid secret), or no events are chosen. For a channel that is not switched on, /status shows state: "disabled". |
| Notifications failing | Notifications → the channel's status and last_error. "held: waiting for a valid clock" = waiting for NTP; the TLS verification (bundle / CA / fingerprint, the host name in the certificate); 3xx is not followed; DNS reachability (prefer an IP address); Send a test event. For e-mail: the server does not offer STARTTLS, a wrong AUTH password, AUTH without TLS not allowed. |
| Storage not mounted | Alarm "The storage partition is not mounted": nothing is stored or sent. If the device held data, restart it once first; only then format it on the System page (formatting erases everything). |
inbox.evicted | The integration did not acknowledge and the quota or the age removed unacknowledged messages. Set up acknowledgements (POST /inbox/ack), then clear the alarm. |
| The API answers 401 / 403 | 401: the token is missing, unknown or revoked (header Authorization: Bearer …). 403: the key lacks the scope, or the client is connected over the gateway's access point. |
| The API answers 503 | By code: not_ready – the store is rebuilt after a start (seconds); busy / timeout – concurrent load, retry after Retry-After; queue_full – 150 messages queued (check on the Status page whether the modem can send); maintenance – a firmware upload is running; storage_error / low_memory – see the alarms on the Status page and the log. |
| "No valid clock" warning | The gateway has no time from NTP nor from the mobile network: the limits do not roll over, verified TLS waits, message times are unknown. Allow outgoing NTP (UDP 123). |
| The firmware was not installed | A foreign or damaged image (another product or board, a bad signature, a truncated file) is refused. An unsigned image is refused while Signed images only is on, else it waits 10 minutes for the confirmation – only in the session that uploaded it; unconfirmed, it is dropped. An older signed version also waits 10 minutes for the confirmation (also with Signed images only). While the firmware just installed is being validated (120 s) no new upload is taken – wait. The upload's result page and the log show why. |
| The previous version runs after an update | The new firmware did not complete 120 s of normal operation (a reset, crash, power cut, a requested restart not validated within 180 s of the first request, or a failed marking as valid) and the gateway went back to the previous one (the rollback is written to the log). Check that the image is for this board and install again; if it repeats, contact the supplier. |
| Forms behind a proxy answer 403 | The proxy rewrites the Host header; keep it (nginx: proxy_set_header Host $host;). |
| Forgotten admin password | reset-password on the serial console, then log in with an empty password and set a new one. |
10. Bezpečnost
Co je chráněno a jak
- Transport: brána nemá HTTPS server; webové rozhraní i API jsou HTTP. Tokeny API a cookie relace jdou v každém požadavku – v otevřené síti je může kdokoli odposlechnout.
- Webové rozhraní: heslo jako PBKDF2-HMAC-SHA256 se solí v NVS; relace v cookie HttpOnly / SameSite=Strict; token formuláře proti CSRF; kontrola
Origin; omezení chybných přihlášení; hlavičkaReferrer-Policy: no-referrer; escapování veškerého obsahu zpráv. - API: tokeny se 128 náhodnými bity, uložen jen SHA-256; oprávnění send / read / admin; okamžité zneplatnění; globální omezení neplatných tokenů; omezení nových spojení.
- Webhook: podpis HMAC-SHA256 s časovým razítkem; HTTPS s ověřením certifikátu (bundle, vlastní CA nebo otisk). Hodnoty vlastních hlaviček a hesla SMTP se nikdy nezobrazují ani nelogují.
- Firmware: podepsané obrazy, cizí obrazy se odmítnou, automatický návrat, když nový firmware nevydrží 120 s běžného provozu; restart ho nikdy neoznačí jako platný.
- Přístupový bod: klientům se nikdy neposkytuje API; obnovovací přístupový bod je WPA2 s náhodným heslem a je ve výchozím stavu vypnutý.
- Log: texty zpráv nikdy, telefonní čísla jen maskovaná.
- Sériová konzole:
reset-passwordareset-networkvyžadují fyzický přístup k zařízení – chraňte ho. - Bez hesla (nové zařízení, po
reset-password) se přihlásí prázdným heslem kdokoli, kdo se k webovému rozhraní dostane, včetně kohokoli v dosahu otevřeného přístupového bodu pro nastavení. Heslo nastavte hned.
Doporučení
- Bránu umístěte do izolované sítě / VLAN, kam mají přístup jen integrované systémy a správci, nebo za reverzní proxy s TLS (nginx, HAProxy, Traefik …), přičemž samotná brána je dostupná jen z proxy. Za proxy zachovejte hlavičku
Host. - LAN nesmí používat podsíť 10.217.88.0/24.
- Webhook provozujte přes
https://s ověřením (bundle nebo vlastní CA);http://jen v izolované síti. Režim INSECURE nepoužívejte. - E-mail přes STARTTLS nebo SMTPS; plain SMTP jen k relay v důvěryhodné síti, AUTH bez TLS jen s účtem, který se nepoužívá k ničemu jinému.
- Pro každý integrovaný systém samostatný API klíč s nejmenšími potřebnými oprávněními a s vlastními limity. Tokeny a secret webhooku ukládejte do úložiště tajemství klienta, ne do zdrojového kódu. Při podezření na únik klíč zneplatněte a vytvořte nový, secret vygenerujte znovu.
- Ponechte ochranu nákladů restriktivní: povolte jen předvolby, které opravdu potřebujete; pamatujte, že mimo +420 se prémiová čísla nekontrolují.
- Zapněte Signed images only. Obnovovací přístupový bod zapínejte jen v případě potřeby.
- Silné heslo správce; zajistěte fyzickou ochranu zařízení (sériová konzole).
- Zajistěte přístup k NTP – bez platného času se limity nepřetáčejí a ověřené TLS čeká.
10. Security notes
What is protected and how
- Transport: the gateway has no HTTPS server; the web interface and the API are HTTP. API tokens and session cookies travel in every request – on an open network anyone listening can take them.
- Web interface: the password as PBKDF2-HMAC-SHA256 with a salt in NVS; sessions in an HttpOnly / SameSite=Strict cookie; a form token against CSRF; the
Origincheck; the wrong-password throttle; the headerReferrer-Policy: no-referrer; every message content escaped. - API: tokens with 128 random bits, only their SHA-256 stored; scopes send / read / admin; immediate revocation; a global throttle of invalid tokens; the new-connection limit.
- Webhook: an HMAC-SHA256 signature with a timestamp; HTTPS with certificate verification (bundle, own CA or fingerprint). Extra header values and SMTP passwords are never shown or logged.
- Firmware: signed images, foreign images refused, automatic rollback when a new firmware does not complete 120 s of normal operation; a restart never marks it valid.
- Access point: the API is never served to its clients; the recovery access point is WPA2 with a random passphrase and is off by default.
- Log: message texts never, phone numbers only masked.
- Serial console:
reset-passwordandreset-networkneed physical access to the device – protect it. - Without a password (a fresh device, after
reset-password) anyone who reaches the web interface logs in with an empty password, including anyone in range of the open setup access point. Set the password at once.
Recommendations
- Place the gateway in an isolated network / VLAN that only the integrating systems and the admins reach, or behind a TLS reverse proxy (nginx, HAProxy, Traefik …) with the gateway itself reachable only from the proxy. Behind a proxy keep the
Hostheader. - The LAN must not use the subnet 10.217.88.0/24.
- Run the webhook over
https://with verification (bundle or own CA);http://only in an isolated network. Do not use the INSECURE mode. - E-mail over STARTTLS or SMTPS; plain SMTP only to a relay in a trusted network, AUTH without TLS only with an account used for nothing else.
- A separate API key for every integrating system, with the least scopes it needs and its own limits. Keep tokens and the webhook secret in the client's secret store, not in source code. On a suspected leak revoke the key and create a new one, and generate a new secret.
- Keep the cost protection restrictive: allow only the prefixes you really need; remember that outside +420 premium numbers are not checked.
- Switch Signed images only on. Switch the recovery access point on only when needed.
- A strong admin password; physical protection of the device (serial console).
- Make sure NTP is reachable – without a valid clock the limits do not roll over and verified TLS waits.
11. Parametry a limity
| Parametr | Hodnota |
|---|---|
| Firmware | 1.0.0, licence GPL-3.0-or-later |
| Procesor / flash | ESP32-WROOM-32E / 16 MB, oddíl LittleFS asi 7,9 MB |
| Modem | SIMCom A7682E, LTE Cat-1, jen SMS |
| Ethernet | LAN8720A, 10/100 Mb/s, DHCP nebo statická adresa |
| Napájení | PoE nebo USB |
| Webové rozhraní / API | HTTP, port 80 |
| Propustnost odesílání | asi 1 část SMS za sekundu |
| Fronta odesílání | 150 zpráv, každá nejvýš 10 částí |
| Délka zprávy | 1 530 septetů GSM-7 / 670 jednotek UCS-2 (10 částí) |
validity / ttl | 60 s – 72 h; výchozí 24 h / 1 h |
| Doručenky | čeká se do sent_at + validity + 1 h; tabulka 384 položek |
| Skládání vícedílných zpráv | nejvýš 64 částí, časový limit 1 h |
| Archiv zpráv | nejvýš asi 3,5 MB (přijaté : odeslané = 55 : 45), retence 90 dní |
| API klíče | nejvýš 4; oprávnění send / read / admin |
| Výchozí ochrana nákladů | předvolba +420; globálně 200 částí / h, 1 000 částí / den |
| Seznamy ochrany nákladů | nejvýš 8 předvoleb (po 8 znacích), nejvýš 8 výjimek (po 16 znacích) |
| Tělo požadavku API | 4 096 bajtů |
| Stránka API | limit 1–50 (výchozí 20), nejvýš 8 kB |
| Souběh | 4 čtecí a 2 zápisové úlohy; nejvýš 6 požadavků současně; požadavek se ukončí po 30 s |
| Idempotence | posledních 500 zpráv s klíčem, 24 h |
| Neplatné tokeny | globálně 10 najednou, pak 1 za 2 s |
| Nová spojení | 40/s celkem (nárazově 80), 30/s z jedné adresy (nárazově 60) |
| Relace správce | nejvýš 4, vyprší po 24 h nečinnosti; 5 chybných hesel = blokace adresy na 60 s |
| Heslo správce | 8–64 znaků |
| Webhook | 1 URL (nejvýš 160 znaků); 20 událostí / 4 kB na požadavek; odpověď do 10 s; odstup 10 s až 15 min; upuštění po 24 h; fronta 256 událostí |
| Secret webhooku | 16–64 tisknutelných znaků ASCII bez mezer |
| Vlastní hlavičky webhooku | nejvýš 4, celkem 256 bajtů |
| Vlastní CA | PEM, nejvýš 4 096 bajtů, kořen + nejvýš 1 mezilehlý |
| nejvýš 4 příjemci; výchozí 30 e-mailů / h; port výchozí 587 (STARTTLS) | |
| Přístupový bod | SMS-GW-XXXXXX, 10.217.88.1/24; nastavovací otevřený, obnovovací WPA2 5 min (nejvýš 30 min) |
| Sériová konzole | 115 200 Bd |
11. Specifications and limits
| Parameter | Value |
|---|---|
| Firmware | 1.0.0, license GPL-3.0-or-later |
| Processor / flash | ESP32-WROOM-32E / 16 MB, LittleFS partition about 7.9 MB |
| Modem | SIMCom A7682E, LTE Cat-1, SMS only |
| Ethernet | LAN8720A, 10/100 Mb/s, DHCP or a static address |
| Power | PoE or USB |
| Web interface / API | HTTP, port 80 |
| Sending throughput | about 1 SMS part a second |
| Send queue | 150 messages of at most 10 parts each |
| Message length | 1,530 GSM-7 septets / 670 UCS-2 units (10 parts) |
validity / ttl | 60 s – 72 h; defaults 24 h / 1 h |
| Delivery reports | awaited until sent_at + validity + 1 h; a table of 384 entries |
| Multi-part joining | at most 64 parts, 1 h timeout |
| Message archive | at most about 3.5 MB (received : sent = 55 : 45), retention 90 days |
| API keys | at most 4; scopes send / read / admin |
| Default cost protection | prefix +420; globally 200 parts / h, 1,000 parts / day |
| Cost protection lists | at most 8 prefixes (8 characters each), at most 8 exceptions (16 characters each) |
| API request body | 4,096 bytes |
| API page | limit 1–50 (default 20), at most 8 kB |
| Concurrency | 4 read and 2 write jobs; at most 6 requests at a time; a request is closed after 30 s |
| Idempotency | the last 500 keyed messages, 24 h |
| Invalid tokens | globally 10 in a burst, then 1 every 2 s |
| New connections | 40/s in all (burst 80), 30/s from one address (burst 60) |
| Admin sessions | at most 4, 24 h idle; 5 wrong passwords = the address locked for 60 s |
| Admin password | 8–64 characters |
| Webhook | 1 URL (at most 160 characters); 20 events / 4 kB per request; answer within 10 s; backoff 10 s to 15 min; given up after 24 h; queue of 256 events |
| Webhook secret | 16–64 printable ASCII characters without spaces |
| Extra webhook headers | at most 4, 256 bytes in all |
| Own CA | PEM, at most 4,096 bytes, a root + at most 1 intermediate |
| at most 4 recipients; default 30 mails / h; default port 587 (STARTTLS) | |
| Access point | SMS-GW-XXXXXX, 10.217.88.1/24; setup open, recovery WPA2 5 min (at most 30 min) |
| Serial console | 115,200 Bd |