{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module WLED.Device
( getLampState,
setLampState
) where
import Data.Aeson (eitherDecodeStrict, encode)
import Data.ByteString (ByteString, toStrict)
import Network.HTTP.Client.Conduit (Request (method), path)
import Network.HTTP.Simple (getResponseBody, httpBS, parseRequest, setRequestBodyJSON)
import WLED.Types (StateComplete, StatePatch)
getLampState :: String -> IO (Either String StateComplete)
getLampState :: String -> IO (Either String StateComplete)
getLampState String
wledUrl = do
Request
req <- String -> IO Request
forall (m :: * -> *). MonadThrow m => String -> m Request
parseRequest String
wledUrl
Response Method
res <- Request -> IO (Response Method)
forall (m :: * -> *). MonadIO m => Request -> m (Response Method)
httpBS Request
req { path = "json/state" }
Either String StateComplete -> IO (Either String StateComplete)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Method -> Either String StateComplete
forall a. FromJSON a => Method -> Either String a
eitherDecodeStrict (Method -> Either String StateComplete)
-> Method -> Either String StateComplete
forall a b. (a -> b) -> a -> b
$ Response Method -> Method
forall a. Response a -> a
getResponseBody Response Method
res)
setLampState :: String -> StatePatch -> IO (ByteString, ByteString)
setLampState :: String -> StatePatch -> IO (Method, Method)
setLampState String
wledUrl StatePatch
patch =
let body :: ByteString
body = StatePatch -> ByteString
forall a. ToJSON a => a -> ByteString
encode StatePatch
patch
in do
Request
req <- String -> IO Request
forall (m :: * -> *). MonadThrow m => String -> m Request
parseRequest String
wledUrl
Response Method
res <- Request -> IO (Response Method)
forall (m :: * -> *). MonadIO m => Request -> m (Response Method)
httpBS (Request -> IO (Response Method))
-> Request -> IO (Response Method)
forall a b. (a -> b) -> a -> b
$ StatePatch -> Request -> Request
forall a. ToJSON a => a -> Request -> Request
setRequestBodyJSON StatePatch
patch Request
req { method = "POST", path = "json/state" }
(Method, Method) -> IO (Method, Method)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (ByteString -> Method
toStrict ByteString
body, Response Method -> Method
forall a. Response a -> a
getResponseBody Response Method
res)