Skip to content

SimpleHome API | MKR1000

Dominik edited this page Aug 31, 2019 · 2 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 for device discovery is not included.

Code

#include <SPI.h>
#include <WiFi101.h>

String json = "{\"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\"}}}";

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

int status = WL_IDLE_STATUS;
WiFiServer server(80);

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.begin(9600);
  WiFi.begin(ssid, pass);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
  }
  printWiFiStatus();
  server.begin();
  digitalWrite(LED_BUILTIN, LOW);
}


void loop() {
  WiFiClient client = server.available();
  if (client) {
    String currentLine = "";
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (c == '\n') {
          if (currentLine.length() == 0) {
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:application/json");
            client.println();
            client.print(json);
            client.println();
            break;
          }
          else {
            currentLine = "";
          }
        }
        else if (c != '\r') {
          currentLine += c;
        }
        if (currentLine.endsWith("GET /commands")) {
          Serial.println("Requested commands");
        }
        else if (currentLine.endsWith("GET /on")) {
          digitalWrite(LED_BUILTIN, HIGH);
          Serial.println("Requested on");
        }
        else if (currentLine.endsWith("GET /off")) {
          digitalWrite(LED_BUILTIN, LOW);
          Serial.println("Requested off");
        }
      }
    }
    client.stop();
  }
}

void printWiFiStatus() {
  Serial.print("\nConnected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  IPAddress ip = WiFi.localIP();
  Serial.println(ip);
  Serial.print("Signal strength (RSSI): ");
  Serial.print(WiFi.RSSI());
  Serial.println("dBm\n");
}
Clone this wiki locally