#include <WiFi.h>
#include <HTTPClient.h>
#define ssid "Lemon"
#define password "12345678"
// สร้าง token https://notify-bot.line.me/th
#define token "7XQi8Yn3oXf5ejXYtH0mvVcT2hEWFfFa4LBKeVfKfqM"
int SW1=15 ;
int SW2=5 ;
int l1=13 ;
int l2=14 ;
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password, 6);
Serial.print("Connecting to WiFi.");
while(WiFi.status() != WL_CONNECTED) { // รอจนกว่าจะเชื่อมต่อ WiFi สำเร็จ
delay(1000);
Serial.print(".");
}
Serial.println("Connected to WiFi");
sendLineNotify("ระบบควบคุมพร้อมทำงาน");
pinMode(SW1, INPUT);
pinMode(SW2, INPUT);
pinMode(l1, OUTPUT);
pinMode(l2, OUTPUT);
}
void loop() {
if(WiFi.status() == WL_CONNECTED) { // ตรวจสอบการเชื่อมต่อ WiFi
int SW1Value = digitalRead(SW1); // อ่านค่าจากเซ็นเซอร์ PIR
int SW2Value = digitalRead(SW2);
if(SW1Value == 0) {
digitalWrite(l1,1);
sendLineNotify("led1 on"); // ส่งข้อความไปยังไลน์
}
if(SW2Value == 0) {
digitalWrite(l1,0);
sendLineNotify("led1 OFF");}
}
}
void sendLineNotify(String message) { // ฟังก์ชันส่งข้อความ
HTTPClient http;
http.begin("https://notify-api.line.me/api/notify");
http.addHeader("Authorization", "Bearer " + String(token));
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
String encodedMessage = "message=" + urlEncode(message);
int httpCode = http.POST(encodedMessage);
if(httpCode > 0) {
String response = http.getString();
}
else {
Serial.println("Error");
}
http.end();
}
String urlEncode(String value) { // ฟังก์ชันเข้ารหัสข้อความผ่าน URL
String encodedValue = "";
char c;
for(size_t i = 0; i < value.length(); i++) {
c = value.charAt(i);
if(isAlphaNumeric(c)) {
encodedValue += c;
}
else {
encodedValue += String('%');
encodedValue += String(c, HEX);
}
}
return encodedValue;
}