}
Serial.println("");
Serial.println("WiFi Connected");
// Start connected devices
dht.begin();
pixel.begin();
// Get certs from file system and load into WiFiSecure client
LittleFS.begin();
File ca = LittleFS.open(CA_CERT_FILE, "r");
if(!ca) {
Serial.println("Couldn't load CA cert");
} else {
size_t certSize = ca.size();
ca_cert = (char *)malloc(certSize);
if (certSize != ca.readBytes(ca_cert, certSize)) {
Serial.println("Loading CA cert failed");
} else {
Serial.println("Loaded CA cert");
rootCert = new BearSSL::X509List(ca_cert);
wifiClient.setTrustAnchors(rootCert);
}
free(ca_cert);
ca.close();
}
// Set time from NTP servers
configTime(TZ_OFFSET * 3600, TZ_DST * 60, "pool.ntp.org", "0.pool.ntp.org");
Serial.println("\nWaiting for time");
unsigned timeout = 5000;
unsigned start = millis();
while (millis() - start < timeout) {
time_t now = time(nullptr);
if (now > (2018 - 1970) * 365 * 24 * 3600) {
break;
}
delay(100);
}
delay(1000); // Wait for time to fully sync
Serial.println("Time sync'd");
time_t now = time(nullptr);
Serial.println(ctime(&now));
// Connect to MQTT - IBM Watson IoT Platform
while(! mqtt.connected()){
if (mqtt.connect(MQTT_DEVICEID, MQTT_USER, MQTT_TOKEN)) { // Token Authentication
Serial.println("MQTT Connected");
mqtt.subscribe(MQTT_TOPIC_DISPLAY);
} else {
Serial.print("last SSL Error = ");
Serial.print(wifiClient.getLastSSLError(msg, 50));
Serial.print(" : ");
Serial.println(msg);
Serial.println("MQTT Failed to connect! ... retrying");
delay(500);
}
}
}
void loop() {
mqtt.loop();
while (!mqtt.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (mqtt.connect(MQTT_DEVICEID, MQTT_USER, MQTT_TOKEN)) {
Serial.println("MQTT Connected");
mqtt.subscribe(MQTT_TOPIC_DISPLAY);
mqtt.loop();
} else {
Serial.print("last SSL Error = ");
Serial.print(wifiClient.getLastSSLError(msg, 50));
Serial.print(" : ");
Serial.println(msg);
Serial.println("MQTT Failed to connect! ... retrying");
delay(500);
}
}
h = dht.readHumidity();
t = dht.readTemperature(); // uncomment this line for centigrade
// t = dht.readTemperature(true); // uncomment this line for Fahrenheit
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
} else {
// Set RGB LED Colour based on temp
b = (t < ALARM_COLD) ? 255 : ((t < WARN_COLD) ? 150 : 0);
r = (t >= ALARM_HOT) ? 255 : ((t > WARN_HOT) ? 150 : 0);
g = (t > ALARM_COLD) ? ((t <= WARN_HOT) ? 255 : ((t < ALARM_HOT) ? 150 : 0)) : 0;
pixel.setPixelColor(0, r, g, b);
pixel.show();
// Send data to Watson IoT Platform