Skip to content

Commit

Permalink
wip: start access point if wifi fails
Browse files Browse the repository at this point in the history
  • Loading branch information
tcsullivan committed Mar 16, 2024
1 parent 7e09b71 commit 05be60c
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 52 deletions.
77 changes: 53 additions & 24 deletions noisemeter-device/noisemeter-device.ino
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ static Storage Creds;
// Uncomment these to disable WiFi and/or data upload
//#define UPLOAD_DISABLED

constexpr auto WIFI_CONNECT_TIMEOUT_MS = 20 * 1000;

const unsigned long UPLOAD_INTERVAL_SEC = 60 * 5; // Upload every 5 mins
// const unsigned long UPLOAD_INTERVAL_SEC = 30; // Upload every 30 secs

Expand Down Expand Up @@ -99,6 +101,10 @@ double Leq_dB = 0;
static std::forward_list<DataPacket> packets;
static Timestamp lastUpload = Timestamp::invalidTimestamp();

[[noreturn]]
static void enterAccessPointMode();
static int tryWifiConnection();

/**
* Initialization routine.
*/
Expand Down Expand Up @@ -130,40 +136,28 @@ void setup() {
packets.emplace_front();

#ifndef UPLOAD_DISABLED
// Run the access point if it is requested or if there are no valid credentials.
bool resetPressed = !digitalRead(PIN_BUTTON);
if (resetPressed || !Creds.valid() || Creds.get(Storage::Entry::SSID).isEmpty()) {
AccessPoint ap (saveNetworkCreds);
bool isAPNeeded = false;

if (!digitalRead(PIN_BUTTON) || !Creds.valid()) {
SERIAL.print("Erasing stored credentials...");
Creds.clear();
SERIAL.println(" done.");

ap.run(); // does not return
isAPNeeded = true;
} else if (tryWifiConnection() < 0 || Timestamp::synchronize() < 0) {
isAPNeeded = true;
}

// Valid credentials: Next step would be to connect to the network.
const auto ssid = Creds.get(Storage::Entry::SSID);

SERIAL.print("Ready to connect to ");
SERIAL.println(ssid);
// Run the access point if it is requested or if there are no valid credentials.
if (isAPNeeded) {
enterAccessPointMode(); // Does not return
}

WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), Creds.get(Storage::Entry::Passkey).c_str());
lastUpload = Timestamp();

// wait for WiFi connection
SERIAL.print("Waiting for WiFi to connect...");
while (WiFi.status() != WL_CONNECTED) {
SERIAL.print(".");
delay(500);
}
SERIAL.println("\nConnected to the WiFi network");
SERIAL.println("Connected to the WiFi network.");
SERIAL.print("Local ESP32 IP: ");
SERIAL.println(WiFi.localIP());

SERIAL.println("Waiting for NTP time sync...");
Timestamp::synchronize();
lastUpload = Timestamp();
SERIAL.print("Current time: ");
SERIAL.println(lastUpload);
#endif // !UPLOAD_DISABLED
Expand Down Expand Up @@ -237,7 +231,7 @@ void saveNetworkCreds(WebServer& httpServer) {
UUID uuid; // generates random UUID

// Confirm that the given credentials will fit in the allocated EEPROM space.
if (Creds.canStore(ssid) && Creds.canStore(psk)) {
if (!ssid.isEmpty() && Creds.canStore(ssid) && Creds.canStore(psk)) {
Creds.set(Storage::Entry::SSID, ssid);
Creds.set(Storage::Entry::Passkey, psk);
Creds.set(Storage::Entry::UUID, uuid.toCharArray());
Expand All @@ -256,6 +250,41 @@ void saveNetworkCreds(WebServer& httpServer) {
SERIAL.println("Error: Invalid network credentials!");
}

void enterAccessPointMode()
{
AccessPoint ap (saveNetworkCreds);

SERIAL.print("Erasing stored credentials...");
Creds.clear();
SERIAL.println(" done.");

ap.run(); // does not return
}

int tryWifiConnection()
{
const auto ssid = Creds.get(Storage::Entry::SSID);

SERIAL.print("Ready to connect to ");
SERIAL.println(ssid);

WiFi.mode(WIFI_STA);
WiFi.begin(ssid.c_str(), Creds.get(Storage::Entry::Passkey).c_str());

// wait for WiFi connection
SERIAL.print("Waiting for WiFi to connect...");
auto start = millis();
bool connected;

do {
connected = WiFi.status() != WL_CONNECTED;
SERIAL.print(".");
delay(500);
} while (!connected && millis() - start < WIFI_CONNECT_TIMEOUT_MS);

return connected ? 0 : -1;
}

String createJSONPayload(String deviceId, const DataPacket& dp)
{
#ifdef BUILD_PLATFORMIO
Expand Down
34 changes: 6 additions & 28 deletions noisemeter-device/timestamp.h
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,14 @@
class Timestamp
{
public:
Timestamp(std::time_t tm_ = std::time(nullptr)):
tm(tm_) {}
Timestamp(std::time_t tm_ = std::time(nullptr));

bool valid() const noexcept {
return tm >= 8 * 3600 * 2;
}
bool valid() const noexcept;
operator String() const noexcept;
double secondsBetween(Timestamp ts) const noexcept;

operator String() const noexcept {
char tsbuf[32];
const auto timeinfo = std::gmtime(&tm);
const auto success = std::strftime(tsbuf, sizeof(tsbuf), "%c", timeinfo) > 0;

return success ? tsbuf : "(error)";
}

auto secondsBetween(Timestamp ts) const noexcept {
return std::difftime(ts.tm, tm);
}

static void synchronize() {
configTime(0, 0, "pool.ntp.org");

do {
delay(1000);
} while (!Timestamp().valid());
}

static Timestamp invalidTimestamp() {
return Timestamp(0);
}
static int synchronize();
static Timestamp invalidTimestamp();

private:
std::time_t tm;
Expand Down

0 comments on commit 05be60c

Please sign in to comment.