Skip to content

Commit 2f09eca

Browse files
committed
Add sendMessageAndWait
1 parent d5d515f commit 2f09eca

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
- Don't provide field selector functions for any types. Using `OverloadedRecordDot` in client code is recommended. We still export `unLifxT` as a normal function, for backward compatibility.
77
- Move much of the implementation detail of `LifxT` has been moved to `Lifx.Lan.Internal`.
88
- Add `Lifx.Lan.Mock.Terminal` module for testing programs without a physical LIFX device.
9+
- Add `sendMessageAndWait` function.
910
- Use `Text` rather than `ByteString` for `label` field of `LightState`.
1011
- Rename `productId` field of `Product` to `id`.
1112
- Update to latest products list.

src/Lifx/Lan.hs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ module Lifx.Lan (
3131
LifxError (..),
3232
ProductLookupError (..),
3333
MonadLifx (..),
34+
sendMessageAndWait,
3435

3536
-- * Responses
3637
StateService (..),
@@ -53,6 +54,7 @@ module Lifx.Lan (
5354
Header (..),
5455
) where
5556

57+
import Control.Concurrent
5658
import Control.Monad
5759
import Control.Monad.Except
5860
import Control.Monad.Extra
@@ -65,6 +67,7 @@ import Data.Fixed
6567
import Data.Foldable
6668
import Data.Functor
6769
import Data.Maybe
70+
import Data.Proxy
6871
import Data.Time
6972
import Data.Word
7073
import Network.Socket
@@ -581,6 +584,22 @@ getProductInfo dev = do
581584
v <- sendMessage dev GetVersion
582585
either (lifxThrow . liftProductLookupError @m) pure $ productLookup v.vendor v.product versionMinor versionMajor
583586

587+
{- Higher-level helpers -}
588+
589+
{- | Like `sendMessage`, but for messages whose effect is not instantaneous (e.g. `SetColor`),
590+
block (using `threadDelay`) until completion.
591+
-}
592+
sendMessageAndWait :: (MonadLifx m, MonadIO m) => Device -> Message () -> m ()
593+
sendMessageAndWait d m = do
594+
sendMessage d m
595+
maybe (pure ()) (liftIO . threadDelay . timeMicros) mt
596+
where
597+
mt = case m of
598+
SetPower{} -> Nothing
599+
SetColor _ t -> Just t
600+
SetLightPower _ t -> Just t
601+
timeMicros t = round $ t * fromInteger (resolution $ Proxy @E6)
602+
584603
{- Util -}
585604

586605
fromIntegralSafe :: forall a b. (Integral a, Integral b, Bounded b) => a -> Maybe b

0 commit comments

Comments
 (0)