Model Train-related Notes Blog -- these are personal notes and musings on the subject of model train control, automation, electronics, or whatever I find interesting. I also have more posts in a blog dedicated to the maintenance of the Randall Museum Model Railroad.

2023-03-04 - SDB: Wifi and Configuration

Category SDB

The Software Defined Blocks project uses an ESP32 with sensors to emulate block activations for a train model railroad.

Wifi offers the typical bootstrap dilemma on all these tiny gizmos: we need to select an SSID and enter some wifi credentials to connect to an existing network.

The typical “Arduino way” to deal with this problem is to encode both the SSID and the password in the Arduino code. That forces users to recompile the Arduino sketch before deploying.

On devices with an sdcard, a work-around is to have users create a small config file with the info that we can read at boot.

Here instead I want to have the traditional “wifi-enabled gizmo” behavior.

An ESP32 running SDB shall offer this behavior:

  • When no configuration is present or a select GPIO override (button, etc) is held at boot, we start a Wifi ad-hoc network.
    • Users then connect to that ad-hoc network. The device presents a web page, letting them enter the minimum Wifi info (SSID, password) we need to connect, then save it in NVS, and “reboot”.
  • If the device boots with a valid configuration, we simply try to connect to that wifi as a client.

I’ve implemented this in the SDB prototype and it works very well. There’s only change I want to make: apparently the ESP-IDF framework lets us provide both an ad-hoc wifi server and connect to a wifi client at the same time.

This is useful for devices like the ESP32-CAM which do not have any single usable GPIO (*) -- we simply need to run the ad-hoc wifi server for a few minutes a boot. The alternative is to rely on the sdcard, which the ESP32-CAM has.

(* The ESP32-CAM has a bunch of GPIOs exposed on the device pins, but they are heavily multiplexed with something else, such as the camera or the sdcard. So if we do not use the sdcard, we suddenly have 3 or 4 usable pins.)

In SDB, the Wifi module is implemented here: https://bitbucket.org/alf-labs/sdb/src/master/src/mod_wifi.h

The implementation is fairly satisfactory and very simple. There are two kind of web pages being served:

  • AP is ad-hoc wifi server for initial configuration.
  • STA is the “regular” wifi client connecting to an existing wifi network.

In both cases, we have an HTML page; a script compresses using gzip and encodes it in a C header, which is then served from the wifi module. Both web pages exchange data with the ESP32 using JSON. This allows the configuration page to fetch properties exposed by either the block modules, the sensor modules, or the server modules, as well as post back updated configuration forms. Live data from the sensors can also be queried.


 Generated on 2024-08-06 by Rig4j 0.1-Exp-e7e2d73