TinyWifiDongle 0.1.0
Header-only USB WiFi dongle for Arduino
Loading...
Searching...
No Matches
CredentialStore.h
Go to the documentation of this file.
1#pragma once
2#include <Arduino.h>
3#include <EEPROM.h>
4
5namespace twd {
6
15 public:
17 bool load() {
18 begin();
19 EEPROM.get(0, data_);
20 return valid();
21 }
22
24 bool valid() const { return data_.magic == kMagic && data_.ssid[0] != 0; }
25
27 bool save(const char* ssid, const char* password) {
28 memset(&data_, 0, sizeof(data_));
29 data_.magic = kMagic;
30 snprintf(data_.ssid, sizeof(data_.ssid), "%s", ssid ? ssid : "");
31 snprintf(data_.password, sizeof(data_.password), "%s", password ? password : "");
32 return write();
33 }
34
36 bool forget() {
37 memset(&data_, 0, sizeof(data_));
38 return write();
39 }
40
42 const char* ssid() const { return data_.ssid; }
43
45 const char* password() const { return data_.password[0] ? data_.password : nullptr; }
46
47 private:
48 static constexpr uint32_t kMagic = 0x54574431; // marks the structure as ours
49 struct Data {
50 uint32_t magic;
51 char ssid[33];
52 char password[65];
53 };
54
55 Data data_ = {};
56 bool begun_ = false;
57
58 void begin() {
59 if (begun_) return;
60 EEPROM.begin(sizeof(Data));
61 begun_ = true;
62 }
63
64 bool write() {
65 begin();
66 EEPROM.put(0, data_);
67 return EEPROM.commit();
68 }
69};
70
71} // namespace twd
Keeps the name and password of one WiFi network in flash.
bool forget()
Removes the saved network. False if the flash could not be written.
bool load()
Reads the flash. Returns true if a network is saved.
const char * ssid() const
Name of the saved network.
bool valid() const
True if a network is saved (after load() or save()).
bool save(const char *ssid, const char *password)
Saves the network; an empty or null password means an open network. False if the flash could not be w...
const char * password() const
Password of the saved network, nullptr if it is an open network.