Skip to content
f1devbinPublic

About

LoRa gateway firmware for ESP32 + SX1278 (433 MHz): long-range IP link to an off-grid site, MQTT, OTA, web UI.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

LoRa Internet Gateway (lora-inet) — ESP32 + SX1278, 433 MHz

Русская версия

LoRa gateway firmware for LILYGO T3 V1.6.1 / LoRa32 V2.1_1.6 boards (ESP32 + SX1278, 433 MHz, ESP-IDF): a long-range point-to-point link that connects an off-grid place without Internet (e.g. a summer house) to a home server. Two services share one radio link:

  • Data channel MQTT ↔ LoRa — sensors and switches at the remote site appear in Home Assistant at home. Works over long range on slow profiles.
  • IP tunnel — real (slow) Internet for phones and laptops at the remote site.
remote site:  sensors / phone ── Wi-Fi ── [CLIENT board] ~~~ LoRa 433 MHz ~~~ [SERVER board] ── Wi-Fi ── router ── Internet
                                                          (optional relays)                     └── MQTT broker ── Home Assistant

One firmware; the role (SERVER, CLIENT, later RELAY) and the services are chosen in the web UI. No Linux host is needed.

Status: experimental. Stages 1–3 are done and bench-tested: configuration and web UI, LoRa link, coverage survey, reliable transport with server polling, JOIN and over-the-air profile changes. No encryption, data channel or IP tunnel yet. See Roadmap.

What to expect

LoRa is slow and half-duplex. Calculated airtime of one frame (SX1278, CR 4/5, preamble 8, explicit header, CRC on):

Profile SF / BW Raw LoRa bitrate 255 B frame 40 B frame
FAST 7 / 500 kHz 21.9 kbit/s 100 ms 21 ms
BALANCED 8 / 250 kHz 6.25 kbit/s 354 ms 77 ms
RANGE 10 / 125 kHz 0.98 kbit/s 2.30 s 0.53 s

Measured so far (stage 3, bench, FAST, application payload of the link test): 12.7 kbit/s server → client and 13.3 kbit/s client → server without loss; 9.9 / 8.8 kbit/s with 20 % of frames lost in each direction (simulated), nothing lost end to end. The tunnel adds IP/TCP overhead. Details: docs/MEASUREMENTS.md.

Design targets (tunnel and relays not measured yet):

Direct Via 1 relay Via 2 relays
Tunnel throughput, FAST 8–12 kbit/s ≤ 4–6 kbit/s (≤ ½) ≤ 2.5–4 kbit/s (≤ ⅓)
Ping, FAST, idle 150–250 ms ×2 ×3
Sensor value / command, RANGE ≈ 1–3 s ×2 ×3

Relays work on the same frequency, so every hop sends each frame again: airtime per frame is multiplied by (hops + 1). The fractions above are upper bounds; hidden nodes, turnaround times and duty-cycle limits make real numbers lower.

The tunnel is good enough for messengers (text), e-mail, SSH and light text pages; not for images, video or calls. The data channel is the robust part: a temperature value costs a few bytes on air.

Hardware

Item Value
Board LILYGO T3 V1.6.1 (a.k.a. LoRa32 V2.1_1.6), without TCXO
MCU ESP32-PICO-D4, 4 MB flash, no PSRAM
Radio SX1278, 433 MHz band (410–525 MHz)
Display SSD1306 128×64, I²C

Where to buy: LILYGO store — LoRa32 / T3 (choose the 433 MHz variant).

Pin map, revisions and how to check your board: docs/HARDWARE.md.

Quick start

Flash from the browser: open f1devbin.github.io/lora-inet in Chrome or Edge, connect the board over USB and install the current build — no toolchain, no command line. The manual build follows.

Requirements: Python 3, PlatformIO Core, a USB data cable.

git clone <this repository> lora-inet && cd lora-inet
python3 -m venv venv && ./venv/bin/pip install platformio esptool

# Optional but recommended: back up the current firmware (e.g. Meshtastic) first
./tools/backup_flash.sh /dev/serial/by-id/usb-1a86_USB_Single_Serial_XXXXXXXXXX-if00 board-a

# Build and flash
./venv/bin/pio run
./venv/bin/esptool --port <port> erase-flash          # first time only: removes old NVS data
./venv/bin/pio run -t upload --upload-port <port>
./venv/bin/pio device monitor -p <port>

# Alternative without PlatformIO at flash time (uses the build output):
#   ESPTOOL=./venv/bin/esptool tools/flash.sh <port> --erase
#   ./venv/bin/python tools/serial_log.py <port> 15 --reset

First configuration:

  1. The display shows the generated password (inverted line at the bottom, below Password:). No display (or a broken one)? Use USB: pass show in a serial terminal (115200 baud), or set your own passwords with ./venv/bin/python tools/set_password.py <port> --ap.
  2. Join Wi-Fi LoRaGW-XXXX (XXXX = last 4 hex digits of the MAC) with that password.
  3. The login page opens by itself (captive portal). If not, open http://10.10.10.10/ — the same address on every device and in every role. Log in with the same password.
  4. The first-setup wizard asks for the role, device name, new AP password and web password (each entered twice, with a "Show" button), the network key (generate on the first board, paste on the others) and, for SERVER, the router network. The router password is tested before anything is saved.
  5. The summary shows what changes and where the web UI will be afterwards (SSID, address, password with a "Show" button). After Apply the board reboots: join the new access point, log in with the new web password and press Confirm within 5 minutes — otherwise the previous settings come back automatically.
  6. LoRa page: pick a profile. All boards must use the same settings.

The management access point stays on in every role. On a SERVER it can be switched off explicitly (Wi-Fi page) once the router uplink works; the web UI is then reachable via the router IP.

The generated password is created once (first start or factory reset) and stored in NVS; reboots and firmware updates do not change it (settings are migrated between firmware versions, never reset). Passwords you set (web UI or USB) are stored permanently. For your own builds you can replace the random first-boot password with a fixed one in src/config_local.h (template src/config_local.example.h) or platformio_override.ini — both are git-ignored. It applies when a device starts with empty config (install with --erase, or after a factory reset).

Updating boards

  • Order: server first, then the clients. The protocol version is checked at JOIN; each firmware also understands the previous version, so an updated server keeps serving old clients. Do not skip a protocol version while an older board is still in use. A mismatch is shown on the display (PROTO S v3 C v2) and as a banner in the web UI. Details: docs/PROTOCOL.md.
  • tools/flash.sh keeps a copy of every flashed firmware (firmware-archive/<version>-<sha>.elf/.bin, not in git). Keep it: a crash dump downloaded from a board can only be decoded with the ELF of exactly that build.

Boards flashed with 0.4.0 or older

Partition table B (two 1.8 MB OTA slots, coredump, statistics) replaced table A after 0.4.0-stage3. A board with table A keeps its settings only if it is migrated with tools/migrate_partitions.sh <port> <full-backup.bin> (make the backup with esptool read-flash 0 ALL, export the survey journal with tools/survey_dump.py <backup> --layout a). Plain tools/flash.sh on a table-A board would leave old data inside the enlarged NVS, and the firmware would then erase the NVS. Details: docs/HARDWARE.md.

Recovery

Dangerous changes — role, AP name/password/channel, turning the management AP off, radio parameters, the first-setup wizard — are applied with automatic rollback: unless you press Confirm (web banner, or config confirm over USB) within the chosen time (default 5 min), the device restores the last known good settings and reboots. The countdown is shown on the OLED (CONFIRM m:ss) and in the web UI. Router credentials are tested before saving and are never stored if the connection fails.

No web UI after a role change. The web UI stays at http://10.10.10.10/ on Wi-Fi LoRaGW-XXXX in every role. Don't confirm — after the timeout the previous settings return. Or press RESET 3 times (recovery mode, below).

Forgot the AP password. Press RESET 3 times, each within 10 s after start → recovery mode for 10 minutes: the management AP comes up with this board's own recovery password, shown on the display (RECOVERY m:ss) and by appass show over USB. The web login accepts it too. Nothing else is changed; set a new password on the Wi-Fi page and the board returns to normal mode after 10 minutes (or reboot). The recovery password is generated per board at first start / factory reset and stored separately.

Mistyped the router password. It is not saved: the web UI shows "wrong password" or "network not found" and the old settings stay.

Broken display (USB only). Serial console, 115200 baud (./venv/bin/python tools/serial_log.py <port> 60 --send "help" or any terminal):

Command Action
role show, role set server|client show / change the role (management AP is kept on), reboots
ap show AP name, address, channel, clients — no password
appass show, appass set <new> show / set the AP password (in recovery: the recovery password)
pass show, pass set <new> web password (show only while it is the generated one)
config show settings without secrets, pending / last-known-good state
config confirm, config rollback confirm a pending change / restore last known good now
factory-reset confirm erase settings
antenna show|yes|no confirm the antenna (enables transmitting)
radio show, radio power <2..17>, radio profile fast|balanced|range radio state and counters; power / profile applied at once (both boards!)
neigh neighbour table: RSSI/SNR, RTT, loss
survey on|off|show, survey mark [note], sd coverage survey, journal state, SD card
lora ping, lora test [count] [size] one PING / link test to the peer (32–255 B frames)

Passwords are printed only by an explicit show command, never in the boot log. Recovery mode over USB: ./venv/bin/python tools/quick_reset.py <port> 3.

Full reset. Press RESET 5 times (each within 10 s after start), or System → Factory reset, or factory-reset confirm over USB. Note: flashing and opening a serial monitor also reset the board; several such resets in quick succession count as presses.

Settings are never lost by a reset or a power failure:

  • Power-ons with a battery below 3.7 V do not count as RESET presses: a dying battery switches the board on and off repeatedly, and before 0.4.1 five such cycles performed a factory reset. Use the RESET sequence on USB power or with a charged battery.
  • Every factory reset keeps the previous settings as a backup. After the reset the setup wizard shows why it happened and offers Restore previous settings (console: config backup, config restore-backup confirm). A completed new setup discards the backup.
  • If the settings storage cannot be read after a power failure, its raw copy is kept in the survey journal partition before it is formatted (System page and boot log show this; read it with esptool read-flash 0x16000 0xA000).

Scenario: summer house ↔ home with Home Assistant (planned, stages 5–7)

Home: SERVER board in Wi-Fi range of the router, connected to the existing MQTT broker (e.g. Mosquitto used by Home Assistant). Summer house: CLIENT board with a built-in MQTT broker; ESPHome/Tasmota devices connect to it over the CLIENT's Wi-Fi.

Planned configuration (web UI, MQTT page):

SERVER  broker: mqtt://<broker-host>:1883, user/password, base topic "lorabridge",
        Home Assistant discovery: on
CLIENT  local broker: on (10.10.10.10:1883)
        remote -> home:  dacha/+/temperature, dacha/water/leak, tele/boiler/STATE
        home -> remote:  cmnd/boiler/POWER
        deadband: 0.2 for temperatures, min interval 10 s, heartbeat 15 min

Resulting topics on the home broker (<id> = CLIENT device ID):

Topic Content
lorabridge/<id>/availability online / offline by LoRa link state (retained)
lorabridge/<id>/rssi, /snr, /last_seen, /battery link metrics
lorabridge/<id>/dacha/kitchen/temperature forwarded sensor value
lorabridge/<id>/set/cmnd/boiler/POWER publish OFF here to switch the boiler at the remote site
lorabridge/<id>/result/cmnd/boiler/POWER delivered / failed — whether the command reached the CLIENT

Commands have the highest priority on air and are acknowledged over LoRa. Values are sent on change only; if the link is down the CLIENT keeps the last value per topic and sends it when the link returns.

Web UI

Pages: Dashboard, Survey, Wi-Fi, LoRa, Neighbours, Network, Security, Diagnostics, System (later: MQTT). English and Russian. High-contrast dark theme, large fonts, works on phones. Live status over WebSocket.

Screenshots will be added after hardware testing of stage 1.

Coverage survey (walk test)

Walk around with the CLIENT board on a battery and see the link to the SERVER on its display; afterwards build a coverage map from the journal and a phone GPS track.

On the board

  • CLIENT display (survey mode): first line big — ↓ server → me RSSI and SNR of the last answer; second line ↑ me → server (how the server heard my PING; links are often asymmetric) and the loss of the last 20 PINGs; level bar 0–5 (SNR margin over the demodulation limit of the spreading factor, the weaker direction counts); seconds since the last answer. No answer for 3 intervals: big NO LINK. Bottom line: profile, power, battery %, journal (SD or F<records> in the internal buffer); DUTY LIMIT: skip when a PING was skipped by the duty-cycle limit.
  • SERVER display: clients two per page (name, seconds ago, RSSI / SNR as heard by the server), pages change every 4 s.
  • LED (also for a board with a broken display): one flash per answer = good (level 4–5), two = medium (2–3), three = poor (0–1).
  • PING interval: 3 s by default, raised automatically on slow profiles so PING+PONG use at most 10 % airtime (RANGE: 9 s). Survey with the same profile and power as in real operation; they are on the display.

Journal

  • microSD card (recommended): one CSV file per session in survey/ on the card (survey_YYYYMMDD_HHMMSS.csv in UTC, survey_sNNNN.csv while the clock is not set). Written through a buffer and synced every 5 s: a power cut loses at most the last few points. FAT32 only (ESP-IDF 6.1 has no exFAT): cards up to 32 GB work as sold, larger ones must be reformatted to FAT32. The card can be inserted or removed while running: a write error or a full card switches to the internal buffer without stopping the survey, the card is retried every 30 s.
  • Without a card: ring buffer in the internal flash, 1280 records (40 KB partition), oldest overwritten, written in batches of 16 to limit flash wear (a power cut can lose up to 16 points / 30 s). Shown as F<n> on the display and "No SD card — buffer n/1280" in the web UI.
  • The clock is set from the phone's browser whenever you open the web UI (the board has no clock battery). Records written before that get their time from the sync record of the same session.
  • Web page Survey: big live values, survey on/off and interval, Mark point with a note, journal status, download of the internal buffer (CSV, JSON) and of the SD files (CSV), delete SD files, clear the buffer. The SERVER keeps its own journal (rx rows: every PING it received) for cross-checking.

Step by step

  1. Both boards on the profile and power you will use; antenna confirmed. SERVER at its final place.
  2. CLIENT: insert a FAT32 microSD card (optional), power it from a battery.
  3. Phone: join LoRaGW-XXXX of the CLIENT, open http://10.10.10.10/ → Survey (this also sets the board clock) → Survey mode on → Save. Or over USB: survey on.
  4. Start a GPS track on the phone (OsmAnd, GPSLogger, any GPX logger).
  5. Walk. Use Mark point (web) for interesting places, with a note.
  6. Back home: download the CSV (Survey page, or take the SD card) and export the GPX track.
  7. Build the map: python3 tools/coverage_map.py survey_20261008_101500.csv track.gpx -o map.html [--geojson map.geojson] [--color level|rssi|snr] — open map.html in a browser (tiles from OpenStreetMap need Internet).
  8. survey off (or uncheck in the web UI) to return to normal operation.

Flashing with a card inserted: the card's MISO line is GPIO2, a strapping pin of the ESP32 (GPIO15 = MOSI is one too). If flashing over USB fails with a card inserted, remove the card for flashing (see docs/HARDWARE.md).

Antenna

Never transmit without an antenna. Without a load the power amplifier of the SX1278 can be damaged. The firmware does not transmit at all until you confirm that the 433 MHz antenna is connected: checkbox in the first-setup wizard or on the LoRa page, or antenna yes over USB. Until then the board only receives, the web UI shows a red banner and the OLED shows TX OFF: antenna?. Settings migrated from older firmware start with transmit off.

For bench tests with both boards on one table use the minimum power (2 dBm, radio power 2 over USB): at a few centimetres the receiver is close to saturation. Range and speed are measured separately with the boards apart; see docs/TESTPLAN.md for the conditions of every measurement.

Legal: 433 MHz

You are responsible for complying with the radio regulations of your country. The defaults are conservative: 434.300 MHz (a 500 kHz channel fits inside 433.05–434.79 MHz), 10 dBm. Frequency, power (2–17 dBm, optional +20 dBm) and the duty-cycle limit (off / 10 % / 1 %) are configurable; the UI warns when settings leave the 433.05–434.79 MHz band or exceed 10 dBm. In many European countries this band allows 10 mW e.r.p. with a duty-cycle limit.

The +20 dBm mode of the SX1278 is limited to 1 % duty cycle by its datasheet; the firmware enforces that limit when the mode is enabled.

Limitations

  • Experimental firmware: LoRa link and reliable transport work; no encryption (stage 4), data channel or tunnel yet. Until stage 4 anyone with a LoRa receiver can read and inject frames.
  • With a duty-cycle limit (e.g. 1 % = 36 s of airtime per hour) the link slows down to what the budget allows (FAST: roughly 70 KB per hour) but stays connected.
  • microSD is always optional: every function works without a card (internal flash with smaller limits); the card only adds space and detail.
  • Half-duplex radio: uplink and downlink share airtime; ping grows under load. Each relay hop cuts throughput further (see above).
  • First HTTPS connection to a new host takes several seconds (TLS handshake is 3–6 KB).
  • Phones generate background traffic; the CLIENT will mark its Wi-Fi as metered.
  • Config and keys are stored in NVS without flash encryption: physical access to the board means access to the secrets.
  • Build: the ESP-IDF port of Mosquitto (planned for the CLIENT's local broker) is compiled with -Wno-error, because the upstream source redefines _GNU_SOURCE and fails under ESP-IDF's warnings-as-errors. Only that component is affected; our code keeps -Werror. See docs/ARCHITECTURE.md.

Roadmap

Proposed order (data channel before the IP tunnel: simpler and immediately useful; OTA before boards are installed remotely). Every stage is also checked without a microSD card.

# Stage Status
1 Hardware, NVS config, role, failsafe AP, web UI, OLED, factory reset, access protection done
2 LoRa link: PING/PONG, RSSI/SNR/RTT/loss, neighbour list, duty-cycle limiter, antenna gate done (bench-tested)
2a Coverage survey: big-font display, two-way RSSI/SNR, journal on microSD / flash, map tool done
3 Reliable transport: server polling, JOIN, selective ACK, window, fragmentation, over-the-air profile change, rescue channel, duty-cycle aware access; protocol v2 done (bench-tested)
3b Traffic accounting base: per client bytes/packets/airtime by type, hourly/daily/monthly buckets in LittleFS, JSON API (docs/API.md); new partition table with OTA slots and coredump next
3c OLED language en/ru (Cyrillic only where needed) planned
4 Encryption: AES-128-CCM payload, network hop tag, X25519 JOIN with server key fingerprint, client allowlist planned
5 Data channel, SERVER side: MQTT client, availability and link metrics, HA discovery planned
6 OTA firmware update planned
7 Data channel, CLIENT side: local broker, topic whitelists and ids, deadband, commands with ACK, on-board sensors (I²C/GPIO) planned
7a Telegram bot on the SERVER: status, traffic per client, notifications (client lost/back, limits, reboot, daily summary) planned
8 CLIENT access point DHCP/DNS + IP tunnel (ICMP, then NAPT); traffic per Wi-Fi device planned
9 DNS cache, UDP, TCP, HTTP, HTTPS; connectivity-check handling planned
10 Built-in speed test, diagnostics planned
11 AUTO radio profile planned
12 Relays: modes off / favourites / whole network / public, hop-tag check, forwarding budget; RELAY-ONLY low-power role planned
13 Android app (Kotlin, android/): survey with phone GPS and the screen off, board status and basic settings over the same HTTP API, APK in GitHub Releases planned

Documentation

FAQ / troubleshooting

The display shows nothing. Check the serial log (115200 baud). The firmware keeps running without a display.

LoRa: NOT FOUND / RegVersion 0x00 or 0xFF. SPI does not answer: wrong board revision or a damaged module. See docs/HARDWARE.md.

The display is broken / missing, where is the password? Over USB. Serial console (115200 baud) commands: help, pass show, pass set <new> (web UI), appass set <new> (Wi-Fi AP, after reboot), id, reboot. Or the script: ./venv/bin/python tools/set_password.py /dev/serial/by-id/<port> --ap (asks for the new password, sets web UI and AP, reboots). USB access is treated like the display: physical access to the board.

I forgot the web password. Recovery mode (RESET 3×): log in with the recovery password from the display (or appass show over USB) and set a new one. Or over USB: pass set <new>. See Recovery.

Upload fails. Remove the microSD card: its MISO line is GPIO2, a strapping pin.

Why not just Meshtastic? Meshtastic carries short text messages. This project carries MQTT values with acknowledged commands and an IP tunnel, between a fixed home and remote site.

License

MIT. All code in this repository is original; third-party material is listed in docs/ARCHITECTURE.md.


По-русски

Прошивка LoRa-шлюза на ESP32 + SX1278 (433 МГц): дальний IP-канал до удалённой площадки, MQTT, OTA-обновления и веб-интерфейс.

About

LoRa gateway firmware for ESP32 + SX1278 (433 MHz): long-range IP link to an off-grid site, MQTT, OTA, web UI.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages