#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <EEPROM.h>
#include <DHT.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#define DHTPIN D1
#define DHTTYPE DHT11
#define BUZZER_PIN D2
#define EEPROM_SIZE 128
DHT dht(DHTPIN, DHTTYPE);
ESP8266WebServer server(80);
DNSServer dnsServer;
float alarmTemp = 30.0;
String wifiSSID = "";
String wifiPASS = "";
bool apMode = true;
float temperature, humidity;
int currentPattern = 1; // tone pattern selection
// Receiver IP (fixed)
IPAddress receiverIP(192,168,4,2);
// Tone patterns (Nokia-style)
int pattern1_freq[] = {1000, 1200, 1000};
int pattern1_dur[] = {200, 200, 400};
int pattern1_len = 3;
int pattern2_freq[] = {800, 1000, 1200, 1400};
int pattern2_dur[] = {150, 150, 150, 300};
int pattern2_len = 4;
int pattern3_freq[] = {1500, 1200, 1000, 1500};
int pattern3_dur[] = {100, 100, 100, 100};
int pattern3_len = 4;
// ------------------- EEPROM -------------------
void saveSettings() {
EEPROM.put(0, alarmTemp);
for(int i=0;i<32;i++) EEPROM.write(10+i, i<wifiSSID.length()?wifiSSID[i]:0);
for(int i=0;i<32;i++) EEPROM.write(42+i, i<wifiPASS.length()?wifiPASS[i]:0);
EEPROM.write(100, apMode?0:1);
EEPROM.write(101, currentPattern);
EEPROM.commit();
}
void loadSettings() {
EEPROM.get(0, alarmTemp);
wifiSSID = ""; wifiPASS = "";
for(int i=0;i<32;i++){ char c=EEPROM.read(10+i); if(c) wifiSSID+=c; }
for(int i=0;i<32;i++){ char c=EEPROM.read(42+i); if(c) wifiPASS+=c; }
apMode = EEPROM.read(100)==0?true:false;
currentPattern = EEPROM.read(101);
if(currentPattern<1 || currentPattern>3) currentPattern=1;
}
// ------------------- AP/STA -------------------
void startAP() {
WiFi.mode(WIFI_AP_STA);
WiFi.softAP("TempAlarm_Link", "12345678");
dnsServer.start(53, "*", WiFi.softAPIP());
Serial.println("AP Mode IP: 192.168.4.1");
tone(BUZZER_PIN, 1000, 200);
}
void startSTA() {
WiFi.mode(WIFI_STA);
WiFi.begin(wifiSSID.c_str(), wifiPASS.c_str());
Serial.print("Connecting to Wi-Fi...");
unsigned long startAttempt = millis();
while(WiFi.status()!=WL_CONNECTED && millis()-startAttempt<10000){
delay(500); Serial.print(".");
}
if(WiFi.status()==WL_CONNECTED){
Serial.println("\nConnected to Wi-Fi");
Serial.print("STA IP: "); Serial.println(WiFi.localIP());
tone(BUZZER_PIN, 1000, 200);
} else {
Serial.println("\nWi-Fi connect failed. Staying in AP mode.");
apMode=true;
saveSettings();
startAP();
}
}
// ------------------- Web page -------------------
String mainPage(){
String ipInfo = apMode? "192.168.4.1" : WiFi.localIP().toString();
String html="<!DOCTYPE html><html><head><meta name='viewport' content='width=device-width, initial-scale=1.0'>";
html+="<style>body{font-family:Arial;text-align:center;padding:20px;} .alarm{background:#d32f2f;color:#fff;} .normal{background:#f4f4f4;color:#333;} input,button{padding:10px;margin:5px;font-size:16px;}</style></head><body id='body' class='normal'>";
html+="<h2>Temperature Alarm System</h2>";
html+="<h4>Device IP: "+ipInfo+"</h4>";
html+="<h3>Temp: <span id='temp'>--</span> °C</h3>";
html+="<h3>Humidity: <span id='hum'>--</span> %</h3>";
html+="<h4>Alarm Threshold: <span id='thr'>"+String(alarmTemp)+"</span> °C</h4>";
html+="<input type='number' id='newThr' placeholder='New Threshold'> <button onclick='setThr()'>Set Threshold</button><br>";
html+="<h4>Wi-Fi Settings</h4>";
html+="<input id='ssid' placeholder='SSID' value='"+wifiSSID+"'><br>";
html+="<input id='pass' type='password' placeholder='Password' value='"+wifiPASS+"'><br>";
html+="<button onclick='setWiFi()'>Save Wi-Fi</button><br>";
html+="<button onclick='resetWiFi()' style='background:red;color:white;'>Reset Wi-Fi</button><br>";
html+="<h4>Select Tone Pattern</h4>";
html+="<button onclick='setPattern(1)'>Pattern 1</button>";
html+="<button onclick='setPattern(2)'>Pattern 2</button>";
html+="<button onclick='setPattern(3)'>Pattern 3</button>";
html+="<script>";
html+="function fetchData(){fetch('/data').then(r=>r.json()).then(d=>{";
html+="document.getElementById('temp').innerText=d.temp;";
html+="document.getElementById('hum').innerText=d.hum;";
html+="document.getElementById('thr').innerText=d.thr;";
html+="if(d.temp>d.thr){document.getElementById('body').className='alarm';}else{document.getElementById('body').className='normal';}";
html+="});}";
html+="function setThr(){fetch('/setThr?val='+document.getElementById('newThr').value).then(()=>fetchData());}";
html+="function setWiFi(){fetch('/setWiFi?ssid='+document.getElementById('ssid').value+'&pass='+document.getElementById('pass').value).then(()=>alert('Wi-Fi saved, rebooting...'));}";
html+="function resetWiFi(){fetch('/resetWiFi').then(()=>alert('Wi-Fi reset, rebooting...'));}";
html+="function setPattern(val){fetch('/setPattern?val='+val).then(()=>alert('Pattern set, saved.'));}";
html+="setInterval(fetchData,1500);fetchData();";
html+="</script></body></html>";
return html;
}
// ------------------- Tone pattern -------------------
void playPattern(){
int *freq; int *dur; int len;
switch(currentPattern){
case 1: freq=pattern1_freq; dur=pattern1_dur; len=pattern1_len; break;
case 2: freq=pattern2_freq; dur=pattern2_dur; len=pattern2_len; break;
case 3: freq=pattern3_freq; dur=pattern3_dur; len=pattern3_len; break;
default: freq=pattern1_freq; dur=pattern1_dur; len=pattern1_len;
}
for(int i=0;i<len;i++){
tone(BUZZER_PIN, freq[i], dur[i]);
delay(dur[i]+50);
}
}
// ------------------- Send beep -------------------
void sendAlarmToReceiver() {
if(WiFi.status()==WL_CONNECTED || WiFi.getMode()==WIFI_AP_STA){
WiFiClient client;
HTTPClient http;
http.begin(client, "http://192.168.4.2/beep");
http.GET();
http.end();
}
}
// ------------------- Setup -------------------
void setup(){
Serial.begin(115200);
EEPROM.begin(EEPROM_SIZE);
dht.begin();
pinMode(BUZZER_PIN, OUTPUT);
digitalWrite(BUZZER_PIN, LOW);
loadSettings();
startAP();
if(!apMode && wifiSSID.length()>0) startSTA();
// Web routes
server.on("/", [](){ server.send(200,"text/html",mainPage()); });
server.on("/data", [](){
String json="{\"temp\":"+String(temperature)+",\"hum\":"+String(humidity)+",\"thr\":"+String(alarmTemp)+"}";
server.send(200,"application/json",json);
});
server.on("/setThr", [](){
if(server.hasArg("val")){ alarmTemp=server.arg("val").toFloat(); saveSettings(); }
server.send(200,"text/plain","OK");
});
server.on("/setWiFi", [](){
if(server.hasArg("ssid") && server.hasArg("pass")){
wifiSSID=server.arg("ssid"); wifiPASS=server.arg("pass"); apMode=false; saveSettings(); ESP.restart();
}
});
server.on("/resetWiFi", [](){
wifiSSID=""; wifiPASS=""; apMode=true; saveSettings(); ESP.restart();
});
server.on("/setPattern", [](){
if(server.hasArg("val")){
currentPattern=server.arg("val").toInt();
saveSettings();
}
server.send(200,"text/plain","OK");
});
server.onNotFound([](){
server.send(404,"text/plain","Not Found");
});
server.begin();
}
// ------------------- Loop -------------------
unsigned long lastSend=0;
void loop(){
temperature=dht.readTemperature();
humidity=dht.readHumidity();
if(!isnan(temperature) && temperature>alarmTemp){
playPattern();
if(millis()-lastSend>500){ sendAlarmToReceiver(); lastSend=millis(); }
} else {
noTone(BUZZER_PIN);
}
dnsServer.processNextRequest();
server.handleClient();
}
Comments
Post a Comment