Last active
April 3, 2016 11:06
-
-
Save qerub/e5de4462f418dbfbf59075c7f5b2ba6a to your computer and use it in GitHub Desktop.
[Clojure] Interacting with LIFX's HTTP API using schemas
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; https://github.com/plumatic/schema | |
;; https://github.com/dakrone/clj-http | |
;; http://api.developer.lifx.com/docs/set-state | |
(ns lifx-http-api | |
(:require [schema.core :as s] | |
[clj-http.client :as http])) | |
(def ^:dynamic *base-url* "https://api.lifx.com/v1/lights") | |
(def ^:dynamic *auth-token* "<get yours at https://cloud.lifx.com/settings>") | |
(defn interact [method operation operation-request-schema operation-response-schema request] | |
(s/validate (merge {:selector s/Str} operation-request-schema) request) | |
(let [response (http/request | |
{:socket-timeout 5000 | |
:conn-timeout 5000 | |
:method method | |
:url (format "%s/%s/%s" *base-url* (:selector request) operation) | |
:headers {"Authorization" (format "Bearer %s" *auth-token*)} | |
:as :json | |
:form-params request})] | |
(s/validate operation-response-schema (:body response)) | |
response)) | |
(defn set-state [request] | |
(let [request-schema {(s/optional-key :power) (s/enum "on" "off") | |
(s/optional-key :color) s/Str | |
(s/optional-key :duration) s/Num} | |
response-schema {:results [{:id s/Str :label s/Str :status s/Str}]}] | |
(interact :put "state" request-schema response-schema request))) | |
(defn power-on-and-off [] | |
(set-state {:selector "all", :power "on"}) | |
(Thread/sleep 1000) | |
(set-state {:selector "all", :power "off"}) | |
nil) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment