#include <WiFi.h>
#include "PubSubClient.h"
#include <WireGuard-ESP32.h>
#include <ESPping.h>
char private_key[] = "gCo1bc5uqrPKEeEpD2onVt4NTXQ5FCkNKqVuQnxEZH4=";
IPAddress local_ip(192, 168, 177, 2);
char public_key[] = "/hv+5FF+Cka4WQQjaEyT4EVDFBo2vXfXJPJg3PKy0Tg=";
char endpoint_address[] = "178.208.79.72"; // IP of Wireguard endpoint to connect to.
int endpoint_port = 13231;
static WireGuard wg;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
//const char* mqttServer = "broker.emqx.io";
//const char* mqttServer = "test.mosquitto.org";
const char* mqttServer = "192.168.12.1";
//const char* mqttServer = "broker.mqttdashboard.com";
int port = 1883;
String stMac;
char mac[50];
char clientId[50];
WiFiClient espClient;
PubSubClient client(espClient);
const int ledPin = 2;
void setup() {
Serial.begin(115200);
randomSeed(analogRead(0));
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
wifiConnect();
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
Serial.println(WiFi.macAddress());
stMac = WiFi.macAddress();
stMac.replace(":", "_");
Serial.println(stMac);
Serial.println("Adjusting system time...");
configTime(9 * 60 * 60, 0, "216.239.35.8");
client.setServer(mqttServer, port);
client.setCallback(callback);
pinMode(ledPin, OUTPUT);
wg.begin(
local_ip, // IP address of the local interface
private_key, // Private key of the local interface
endpoint_address, // Address of the endpoint peer.
public_key, // Public key of the endpoint peer.
endpoint_port);
}
void wifiConnect() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password, 6);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
}
void mqttReconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
long r = random(1000);
sprintf(clientId, "clientId-%ld", r);
if (client.connect(clientId)) {
Serial.print(clientId);
Serial.println(" connected");
client.subscribe("MiftahLed/1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void callback(char* topic, byte* message, unsigned int length) {
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
String stMessage;
for (int i = 0; i < length; i++) {
Serial.print((char)message[i]);
stMessage += (char)message[i];
}
Serial.println();
if (String(topic) == "lIVECODING/led") {
Serial.print("Changing output to ");
if(stMessage == "on"){
Serial.println("on");
digitalWrite(ledPin, HIGH);
}
else if(stMessage == "off"){
Serial.println("off");
digitalWrite(ledPin, LOW);
}
}
}
void loop() {
delay(10);
bool success = Ping.ping("192.168.12.1", 3);
if(!success){
Serial.println("Ping failed");
return;
}
Serial.println("Ping succesful.");
delay(100);
if (!client.connected()) {
mqttReconnect();
}
client.loop();
}