diff --git a/base-firmware/Makefile-user.mk b/base-firmware/Makefile-user.mk index 73a4d8f..5711392 100644 --- a/base-firmware/Makefile-user.mk +++ b/base-firmware/Makefile-user.mk @@ -1,2 +1,3 @@ SPIFF_SIZE = 196600 DISABLE_SPIFFS = 0 +ENABLE_SSL = 1 diff --git a/spejsiot/SpejsNode.cpp b/spejsiot/SpejsNode.cpp index 61cf223..579d436 100644 --- a/spejsiot/SpejsNode.cpp +++ b/spejsiot/SpejsNode.cpp @@ -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(¤tSlot)) { @@ -48,12 +55,18 @@ void SpejsNode::loadJSON(std::vector 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 initializers) { } } + // Broker configuration + if (root.containsKey("broker")) { + auto brokerPort = root.containsKey("brokerPort") ? root["brokerPort"] : 1883; + brokerUseTLS = root["brokerUseTLS"]; + brokerURL = root["broker"].as(); + + String hash = root.get("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("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(); diff --git a/spejsiot/SpejsNode.h b/spejsiot/SpejsNode.h index 17123fa..cc61ca8 100644 --- a/spejsiot/SpejsNode.h +++ b/spejsiot/SpejsNode.h @@ -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;