SpejsNode: JSON broker configuration & initial TLS setup

settings
informatic 2019-05-08 16:09:44 +02:00
parent 517ceea15c
commit 19a58cf28f
3 changed files with 45 additions and 4 deletions

View File

@ -1,2 +1,3 @@
SPIFF_SIZE = 196600
DISABLE_SPIFFS = 0
ENABLE_SSL = 1

View File

@ -6,8 +6,15 @@
#define CONFIG_FILE "config.json"
uint8_t hexToInt(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return c - 'a' + 10;
}
void SpejsNode::init(bool debug) {
deviceID = WifiStation.getMAC().substring(6, 12);
brokerClient = "iot-" + deviceID;
currentSlot = 0;
if(!rboot_get_last_boot_rom(&currentSlot)) {
@ -48,12 +55,18 @@ void SpejsNode::loadJSON(std::vector<EndpointInitializer> initializers) {
#endif
DynamicJsonBuffer jsonBuffer;
if (fileExist(CONFIG_FILE)) {
int size = fileGetSize(CONFIG_FILE);
debugf("Found config file, %d bytes", size);
char* jsonString = new char[size + 1];
fileGetContent(CONFIG_FILE, jsonString, size + 1);
JsonObject& root = jsonBuffer.parseObject(jsonString);
if (!root.success()) {
debugf("invalid config");
return;
}
if (root.containsKey("name"))
deviceType = (root["name"]).asString();
@ -72,6 +85,25 @@ void SpejsNode::loadJSON(std::vector<EndpointInitializer> initializers) {
}
}
// Broker configuration
if (root.containsKey("broker")) {
auto brokerPort = root.containsKey("brokerPort") ? root["brokerPort"] : 1883;
brokerUseTLS = root["brokerUseTLS"];
brokerURL = root["broker"].as<String>();
String hash = root.get<String>("brokerSHA1");
if ((hash.length() + 1) % 3 == 0) {
int hashLength = (hash.length() + 1) / 3;
uint8_t* hashBlob = new uint8_t[hashLength];
for (int i = 0; i < hashLength; i++) {
hashBlob[i] = hexToInt(hash[3*i]) << 4 | hexToInt(hash[3*i+1]);
}
fingerprints.certSha1 = hashBlob;
}
}
JsonObject& data = root.get<JsonObject&>("endpoints");
for (auto it: data) {
bool found = false;
@ -164,12 +196,13 @@ void SpejsNode::onConnected() {
mqtt.setWill(DEV_TOPIC("$online"), "false", 1, true);
#ifdef ENABLE_SSL
const uint8_t sha1Fingerprint[] = SSL_FINGERPRINT;
mqtt.addSslOptions(SSL_SERVER_VERIFY_LATER);
mqtt.setSslFingerprint(sha1Fingerprint, 20);
if (brokerUseTLS) {
mqtt.addSslOptions(SSL_SERVER_VERIFY_LATER);
mqtt.pinCertificate(fingerprints);
}
#endif
mqtt.connect(brokerURL, "iot-" + deviceID);
mqtt.connect(brokerURL, brokerClient);
for(unsigned int i = 0 ; i < endpoints.count() ; i++) {
endpoints.valueAt(i)->onConnected();

View File

@ -76,7 +76,14 @@ protected:
String wifiSSID = WIFI_SSID;
String wifiPassword = WIFI_PWD;
String brokerURL = "mqtt://" MQTT_BROKER;
String brokerClient;
bool brokerUseTLS = false;
#ifdef ENABLE_SSL
SslFingerprints fingerprints;
#endif
public:
MqttClient mqtt;
HttpServer http;