#include "WiFi.h"
#include "HTTPClient.h"
#include "ArduinoJson.h"
// Outlet information
String deviceSN = "10796572";
String api_key = "ADu2FL4V7LdfprFNL9xpKkbVw873";
String query_url = "http://service.wf8266.com/api/mqtt/" + \
deviceSN + "/RequestState/" + api_key;
String switch_off_url = "http://service.wf8266.com/api/mqtt/" + \
deviceSN + "/GPIO/" + api_key + "/12,0";
String switch_on_url = "http://service.wf8266.com/api/mqtt/" + \
deviceSN + "/GPIO/" + api_key + "/12,1";
const int BUTTON_PIN = 15; // Button Pin
const int LED_PIN = 2;
// The button state is initialized to not pressed
int lastButtonState = HIGH;
int ledState = LOW; // LED initial state
HTTPClient http; // Create http client object
// Request outlet switching
void switchOutlet(String switch_url, int ledState) {
bool success = false;
HTTPClient http;
while (!success){
http.begin(switch_url);
//Connection request and response status code
int httpCode = http.GET();
Serial.printf("httpCode=%d\n", httpCode);
if (httpCode == HTTP_CODE_OK){
digitalWrite(LED_PIN, !ledState);
Serial.println("Outlet already switched");
success = true;
}
else {
Serial.println("Error on HTTP request");
delay(5000); // 等待 2 秒後重試
}
http.end(); // Connection end
}
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
pinMode(BUTTON_PIN, INPUT_PULLUP);
// setup WiFi
Serial.println("Initializing WiFi ...");
WiFi.mode(WIFI_STA);
WiFi.disconnect(); // 無線初始化
Serial.print("Connecting to WiFi ");
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print(" connected!");
Serial.println("");
}
void loop() {
int reading = digitalRead(BUTTON_PIN);
//If the button state changes
if (reading != lastButtonState) {
// 延遲50毫秒以過濾按鈕彈跳
delay(50);
// 再次讀取按鈕狀態,確認是否穩定
reading = digitalRead(BUTTON_PIN);
// 如果按鈕確實發生變化
if (reading != lastButtonState) {
// 更新按鈕狀態
lastButtonState = reading;
// 當按鈕被按下(狀態從高變低)時切換 LED
if (reading == LOW) {
Serial.println("Button pressed!");
int ledState = digitalRead(LED_PIN);
if (ledState == 0){
switchOutlet(switch_on_url, ledState);
}
else if (ledState == 1){
switchOutlet(switch_off_url, ledState);
}
}
}
}
}