Skip to content

Instantly share code, notes, and snippets.

@qerub
Last active April 3, 2016 11:06
Show Gist options
  • Save qerub/e5de4462f418dbfbf59075c7f5b2ba6a to your computer and use it in GitHub Desktop.
Save qerub/e5de4462f418dbfbf59075c7f5b2ba6a to your computer and use it in GitHub Desktop.
[Clojure] Interacting with LIFX's HTTP API using schemas
;; 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