-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcopswitch.ino
82 lines (68 loc) · 2.37 KB
/
copswitch.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <BLEAdvertisedDevice.h>
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* hassServer = "http://YOUR_HASS_SERVER_IP:8123";
const char* hassToken = "Bearer YOUR_LONG_LIVED_ACCESS_TOKEN";
bool deviceFound = false;
unsigned long lastDetectedTimestamp = 0;
const unsigned long detectionInterval = 60000; // 1 minute in milliseconds
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
void onResult(BLEAdvertisedDevice advertisedDevice) {
String address = advertisedDevice.getAddress().toString().c_str();
if (address.startsWith("00:25:df", false)) {
deviceFound = true;
lastDetectedTimestamp = millis();
}
}
};
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Initialize BLE
BLEDevice::init("");
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
pBLEScan->setInterval(100);
pBLEScan->setWindow(99);
}
void updateHomeAssistantSwitch(bool state) {
HTTPClient http;
String url = String(hassServer) + "/api/states/switch.esp32c3_ble_switch";
String payload = "{\"state\": \"" + (state ? "on" : "off") + "\"}";
http.begin(url);
http.addHeader("Authorization", hassToken);
http.addHeader("Content-Type", "application/json");
int httpResponseCode = http.POST(payload);
if (httpResponseCode > 0) {
String response = http.getString();
Serial.println(httpResponseCode);
Serial.println(response);
} else {
Serial.print("Error on sending POST: ");
Serial.println(httpResponseCode);
}
http.end();
}
void loop() {
deviceFound = false;
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->start(5, false); // Scan for 5 seconds
if (deviceFound || (millis() - lastDetectedTimestamp <= detectionInterval)) {
updateHomeAssistantSwitch(true);
} else {
updateHomeAssistantSwitch(false);
}
delay(5000); // Delay for 5 seconds before next scan
}