Beacon_scaner/src/main.cpp
2024-09-30 12:56:09 +02:00

214 lines
6.4 KiB
C++

#include <Arduino.h>
/*
ibeacon oder Beliebiger BLE Gerät Präsenz Überwachung mit Relais Anwesenheitserkennung
Michael Dworkin http://esp32-server.de/
Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp
Ported to Arduino ESP32 by Evandro Copercini
*/
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <BLEAddress.h>
#include <Ticker.h>
#include <WiFi.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
#define mqtt_port 1883
//cf:d7:ab:1f:24:2c
String Adresse = TRANSPONDER; // Bluetooth Adresse die zu Anwesenheitserkennung überwacht wird ET585
//String Adresse = "cf:d7:ab:1f:24:2c"; // Bluetooth Adresse die zu Anwesenheitserkennung überwacht wird Holy-IOT
const int RelaisPin = LED_BUILTIN; // Pin an dem Relais hängt
int Verzoegerung = 30; // Auschaltverzögerung wenn das Signal von BLE ibeacon fehlt
int VerzoegerungZaeler = 0;
//long int ZZ = 0;
Ticker Tic;
static BLEAddress *pServerAddress;
BLEScan* pBLEScan ;
int scanTime = 5; //In seconds
long int Feldstaerke;
// WiFI
IPAddress ip;
IPAddress gateway;
IPAddress subnet(255,255,255,0);
IPAddress dns;
IPAddress secondaryDNS(8, 8, 8, 8);
String hostname = NAME;
const char *MyIP = KMYIP;
char msg[20];
char clientName[30];
char topic[50];
bool gefunden = false;
const char* mqtt_zentrale = mqtt_server;
void callback(char* topic1, byte* payload, unsigned int length) {
#ifdef DEBUG
Serial.print("Message arrived [");
Serial.print(topic1);
Serial.print("] ");
#endif
for (int i = 0; i < length; i++) {
msg[i] = (char)payload[i];
}
msg[length] = '\0';
}
void reconnect() {
sprintf(clientName, "%s%s", "BLE", "_Gate" );
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect(clientName)) {
/* MQTTStatus.setPic(3); */
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
static void setup_wifi() {
long ErrCount = 0;
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.print(STASSID);
Serial.print(" ");
// WiFi.forceSleepWake();
delay( 1 );
WiFi.persistent( false );
WiFi.setHostname(hostname.c_str()); //define hostname
WiFi.mode( WIFI_STA );
if (!ip.fromString(MyIP)) { // try to parse into the IPAddress
Serial.println("UnParsable IP");
}
if (!dns.fromString(DNS)) { // try to parse into the IPAddress
Serial.println("UnParsable DNS");
}
if (!gateway.fromString(GATEWAY)) { // try to parse into the IPAddress
Serial.println("UnParsable GATEWAY");
}
//WiFi.config( ip, dns, gateway, subnet );
if (!WiFi.config(ip, gateway, subnet, dns, secondaryDNS))
{
Serial.println("STA Failed to configure");
}
WiFi.begin (STASSID, STAPSK);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
ErrCount ++;
if (ErrCount >= 20){
delay(200);
ESP.restart();
}
}
Serial.println(" WiFi connected");
client.setServer(mqtt_server, mqtt_port);
client.setCallback(callback);
Serial.print("IP address: \t");
Serial.println(WiFi.localIP());
}
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks
{
void onResult(BLEAdvertisedDevice advertisedDevice) // passiert wenn BLE Device ( beacon ) gefunden wurde
{
//Serial.print(ZZ); Serial.print("\t");
Serial.print(advertisedDevice.getAddress().toString().c_str()); // ibeacon Adresse anzeigen
Serial.print(" RSSI: ");
Serial.print(advertisedDevice.getRSSI());
/* if (advertisedDevice.haveName()) {
Serial.print(" Device name: ");
Serial.print(advertisedDevice.getName().c_str());
} */
if (advertisedDevice.getAddress().equals(*pServerAddress)and (advertisedDevice.getRSSI() > -85)) // ibeacon Adresse Vergleichen
{
Serial.print(" Ueberwachte Adresse"); // wenn überwache Adresse gefunden wurde
if (advertisedDevice.haveName()) {
Serial.print(" Device name: ");
Serial.print(advertisedDevice.getName().c_str());
}
Serial.print(" RSSI: ");
Serial.print(advertisedDevice.getRSSI());
Serial.print(" dB ");
/* Serial.print(advertisedDevice.getTXPower());
Serial.print(" "); */
digitalWrite (RelaisPin, HIGH); // Relais Einschalten
VerzoegerungZaeler = 0; // Ausschaltverzögerung zurücksetzen
advertisedDevice.getScan()->stop(); // Scanvorgang beenden
gefunden = true;
} // Found our server
Serial.println("");
}
};
void SekundenTic() // Wird jede Sekunde ausgefüert
{
VerzoegerungZaeler++; // Sekundenzähler
//ZZ++;
if (VerzoegerungZaeler >= Verzoegerung){
digitalWrite (RelaisPin, LOW); // Wenn Verzögerungszeit erreicht wurde Auschalten
/* sprintf(topic, "%s%ld%s", "hjk/devices/", clientName, "/telemetry/status" );
client.publish(topic, "FERN", true); */
gefunden = false;
}
}
void setup()
{
pinMode (RelaisPin, OUTPUT);
digitalWrite (RelaisPin, LOW);
Serial.begin(115200);
Serial.println("");
setup_wifi();
Serial.println("Starte BLE Scanner");
pServerAddress = new BLEAddress(Adresse.c_str());
BLEDevice::init("");
pBLEScan = BLEDevice::getScan(); //create new scan
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster
Tic.attach( 1,SekundenTic);
}
void loop()
{
if (!client.connected()) {
reconnect();
}
client.loop();
pBLEScan->start(scanTime);
if (gefunden == true){
sprintf(topic, "%s%s%s", "hjk/devices/", ORT, "/telemetry/status" );
client.publish(topic, "DA", true);
Serial.println();
Serial.print(topic); Serial.println(" DA");
} else {
sprintf(topic, "%s%s%s", "hjk/devices/", ORT, "/telemetry/status" );
client.publish(topic, "FERN", true);
Serial.println();
Serial.print(topic); Serial.println(" FERN");
}
delay(2000); // Alle 2s nach ibeacon scannen
}