#include <Wire.h> //Import the required libraries
#if defined(ESP32)
#include <WiFiMulti.h>
WiFiMulti wifiMulti;
#define DEVICE "ESP32"
#elif defined(ESP8266)
#include <ESP8266WiFiMulti.h>
ESP8266WiFiMulti wifiMulti;
#define DEVICE "ESP8266"
#endif
#include "time.h"
#define DEVICE "ESP32"
#include <PubSubClient.h>
#define TZ_INFO "ICT-7" //InfluxDB v2 timezone
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
#define WIFI_SSID "Wokwi-GUEST" //Network Name
#define WIFI_PASSWORD ""
// Connecting to the WIFI network
// #include "AlarmTone.h"
const int LED_PIN = 12;
// AlarmTone alarmTone;
int inputPin = 2; // choose the input pin (for PIR sensor)
int pirState = LOW; // we start, assuming no motion detected
int val = 0; // variable for reading the pin status
// Variable to save current epoch time
unsigned long epochTime;
// #define INFLUXDB_URL "https://us-east-1-1.aws.cloud2.influxdata.com" //InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries)
// #define INFLUXDB_TOKEN "pnRjTVPQ3g_08AtroQzHFIgSohnY58lEu-ac4_9QV4Wql5rmrObNawNmsCknw-coSkvxa81y7YgClTk06LESgA==" //InfluxDB v2 server or cloud API token (Use: InfluxDB UI -> Data -> API Tokens -> <select token>)
// #define INFLUXDB_ORG "[email protected]"
// // #define INFLUXDB_ORG "7ed53ddf00fdbd0d" //InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids ) //InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
// #define INFLUXDB_BUCKET "PIR-MOTION-SENSOR"
//InfluxDB v2 bucket name (Use: InfluxDB UI -> Data -> Buckets)
// InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); //InfluxDB client instance with preconfigured InfluxCloud certificate
// Point sensor("PIR-MOTION-SENSOR");
String stMac;
char mac[50];
char clientId[50];
const char* mqtt_server = "broker.emqx.io";
const int mqtt_port = 1883;
// const char* mqtt_server = "broker.mqttdashboard.com";
// const int mqtt_port = 8000;
WiFiClient espClient;
PubSubClient client(espClient);
// Create variable to hold mqtt messages
#define MSG_BUFFER_SIZE (100)
char msg[MSG_BUFFER_SIZE];
void setup_wifi() {
delay(10);
// WiFi.mode(WIFI_STA);
// WiFi.begin(WIFI_SSID, WIFI_PASSWORD, 6); //Setup wifi connection
// Serial.print("Connecting to wifi"); //Connect to WiFi
// while (WiFi.status() != WL_CONNECTED)
// {
// Serial.print(".");
// delay(100);
// }
// Serial.println();
WiFi.mode(WIFI_STA); //Setup wifi connection
wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi"); //Connect to WiFi
while (wifiMulti.run() != WL_CONNECTED)
{
Serial.print(".");
delay(100);
}
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);
setup_mqtt();
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov"); //Accurate time is necessary for certificate validation and writing in batches
configTime(0, 0, "pool.ntp.org");
// delay(100);
// if (client.validateConnection()) //Check server connection
// {
// Serial.print("Connected to InfluxDB: ");
// Serial.println(client.getServerUrl());
// }
// else
// {
// Serial.print("InfluxDB connection failed: ");
// Serial.println(client.getLastErrorMessage());
// }
}
void setup_mqtt() {
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
}
void TurnOnLight() {
digitalWrite(LED_PIN, HIGH);
}
void TurnOffLight() {
digitalWrite(LED_PIN, LOW);
}
// Function that gets current epoch time
unsigned long getTime() {
time_t now;
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
//Serial.println("Failed to obtain time");
return(0);
}
time(&now);
Serial.print("EpochTime: ");
Serial.println(now);
return now;
}
void reconnect() {
// Loop until we're reconnected
epochTime = getTime();
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
long r = random(1000);
sprintf(clientId, "clientId-%ld", r);
// Create a random client ID
// String clientId = "clientId-";
// String clientId = "mqttx_086b15c4";
// clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId)) {
Serial.println("connected");
// Once connected, publish an announcement...
String message = String("PIR-MOTION-SENSOR,device="+String(DEVICE)+" connected=1");
message.toCharArray(msg, message.length()+1);
client.publish("PIR-MOTION-SENSOR/1", msg);
// ... and resubscribe
client.subscribe("PIR-MOTION-SENSOR/1");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
setup_mqtt();
}
}
}
void callback(char *topic, byte *payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char) payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
// sensor.addTag("device", DEVICE); //Add tag(s) - repeat as required
// sensor.addTag("SSID", WIFI_SSID);
setup_wifi();
pinMode(inputPin, INPUT); // declare sensor as input
pinMode(LED_PIN, OUTPUT);
// alarmTone.begin(SPEAKER_PIN);
}
void loop() {
val = digitalRead(inputPin); // read input value()
epochTime = getTime();
// sensor.clearFields(); //Clear fields for reusing the point. Tags will remain untouched
// sensor.addField("pirState", val); // Store measured value into point
// if (WiFi.status() != WL_CONNECTED) //Check WiFi connection and reconnect if needed
// Serial.println("Wifi connection lost");
// setup_wifi();
if (wifiMulti.run() != WL_CONNECTED) //Check WiFi connection and reconnect if needed
Serial.println("Wifi connection lost");
if (!client.connected()) {
reconnect();
}
if (val == HIGH) { // check if the input is HIGH
TurnOnLight(); // turn LED ON
// alarmTone.play();
if (pirState == LOW) {
// we have just turned on
Serial.println("Motion detected!");
// We only want to print on the output change, not state
pirState = HIGH;
}
} else {
// turn LED OFF
// alarmTone.stop();
TurnOffLight();
if (pirState == HIGH) {
// we have just turned of
Serial.println("Motion ended!");
// We only want to print on the output change, not state
pirState = LOW;
}
}
String message = String("PIR-MOTION-SENSOR,device="+String(DEVICE)+" pirState="+String(pirState)+" ");
message.toCharArray(msg, message.length()+1);
Serial.println(msg);
client.publish("PIR-MOTION-SENSOR/1", msg);
Serial.println("Wait 1s");
delay(1000);
}