#include <WiFi.h>
#include <string.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define WIFI_CHANNEL 6
namespace led
{
constexpr uint8_t pin = 33;
constexpr uint8_t minValue = 0;
constexpr uint8_t maxValue = 255;
}
// MQTT Broker
namespace mqtt
{
namespace broker
{
constexpr auto url = "b8c171f53af94fddbf33ee09ab2fe0e5.s1.eu.hivemq.cloud";
constexpr auto port = 8883;
};
namespace client
{
constexpr auto username = "lab7.3-actuator";
constexpr auto password = "Lab7.3-actuator";
};
const String subject("intensity");
}; // MQTT
void callback(char* topic, byte* payload, unsigned int length);
void reconnect();
void setLightIntensity(uint8_t intensity);
WiFiClientSecure wifiClient;
PubSubClient pubSubClient(wifiClient);
void setup() {
pinMode(led::pin, OUTPUT);
Serial.begin(9600);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
while (WiFi.status() != WL_CONNECTED)
delay(100);
wifiClient.setInsecure();
pubSubClient.setServer(mqtt::broker::url, mqtt::broker::port)
.setCallback(callback);
}
void loop() {
if (!pubSubClient.connected()) reconnect();
pubSubClient.loop();
delay(500);
}
void callback(char* topic, byte* payload, unsigned int length)
{
String incommingMessage;
for (unsigned int i = 0; i < length; ++i)
incommingMessage += static_cast<char>(payload[i]);
const uint8_t intensity = incommingMessage.toInt();
setLightIntensity(intensity);
}
void reconnect()
{
while (!pubSubClient.connected())
{
Serial.println("Try to connect to MQTT server.");
if (pubSubClient.connect("1", mqtt::client::username, mqtt::client::password))
{
Serial.println("Connected.");
pubSubClient.subscribe(mqtt::subject.c_str());
}
else
{
Serial.println("Fail to connect. Retry in 3 sec.");
delay(3000);
}
}
}
void setLightIntensity(uint8_t intensity)
{
Serial.println(String("Set intensity to ") + intensity + "%");
const auto value = map(intensity, 0, 100, led::minValue, led::maxValue);
analogWrite(led::pin, value);
}