Skip to content

SimpleHome API | ESP8266

Dominik edited this page Aug 25, 2019 · 3 revisions

About This Example

This example lets you turn the built-in LED on and off.
Do not forget to enter your SECRET_SSID and SECRET_PASS.

Code

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

String commands = "{\"commands\":{\"on\":{\"title\":\"Turn on the LED\",\"summary\":\"Turns on the on-board LED\"},\"off\":{\"title\":\"Turn off the LED\",\"summary\":\"Turns off the on-board LED\"}}}";
String toastOn = "{\"toast\":\"Turned on the LED\"}";
String toastOff = "{\"toast\":\"Turned off the LED\"}";

#include "arduino_secrets.h"
const char* ssid = SECRET_SSID;
const char* password = SECRET_PASS;

ESP8266WebServer server(80);

void handleCommands() {
  server.send(200, "application/json", commands);
  Serial.println("Requested commands");
}

void handleOn() {
  digitalWrite(LED_BUILTIN, 0);
  server.send(200, "application/json", toastOn);
  Serial.println("Requested on");
}

void handleOff() {
  digitalWrite(LED_BUILTIN, 1);
  server.send(200, "application/json", toastOff);
  Serial.println("Requested off");
}


void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, 0);
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.hostname("ESP8266-SimpleHome-API-v1");
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  Serial.print("\nConnected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Signal strength (RSSI): ");
  Serial.print(WiFi.RSSI());
  Serial.println("dBm\n");

  server.on("/commands", handleCommands);
  server.on("/on", handleOn);
  server.on("/off", handleOff);
  server.begin();
  digitalWrite(LED_BUILTIN, 1);
}

void loop() {
  server.handleClient();
}
Clone this wiki locally