{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module HomeAssistant.Runtime.Connection ( readerAction , writerAction , dispatchService , encodeService , isTriggerEvent ) where import Control.Concurrent.STM ( atomically , readTChan , readTVar , retry , writeTChan , writeTVar ) import Control.Concurrent (threadDelay) import Control.Exception.Annotated (throw) import Control.Lens ((^?)) import Control.Monad (forever, forM_, when) import Data.Aeson (Value, eitherDecode, encode, object, (.=)) import Data.Aeson.Lens (key, _String) import qualified Data.Set as S import qualified Data.Text as T import Data.Void (Void) import HomeAssistant.Controller (Service (..), Target (..)) import HomeAssistant.Runtime.Bus import HomeAssistant.Runtime.Flags (isEnabled) import HomeAssistant.Runtime.Supervisor (Fatal (..)) import qualified Network.WebSockets as WS import Katip (sl, logFM, Severity (..), ls, Namespace (Namespace), KatipContext, katipAddNamespace, katipAddContext, logLocM) import Data.UUID (toText) import AFRP (Request(..), Event(..)) import Control.Monad.IO.Class (liftIO, MonadIO) import HomeAssistant.Runtime.RateLimit (RateLimited, RateLimiter, runRateLimited) import GHC.Stack (HasCallStack) import UnliftIO (MonadUnliftIO, race, withRunInIO) import Control.Monad.Catch (MonadCatch, onException) -- | Connect, authenticate, subscribe, then receive and broadcast forever. -- Restarting this action reconnects. All setup sends happen before the -- connection is published in the bus, so only the writer sends afterwards. readerAction :: (MonadCatch m, HasCallStack, KatipContext m, MonadUnliftIO m, MonadIO m) => String -> Int -> String -> S.Set T.Text -> Bus -> m Void readerAction host port token ents bus = katipAddNamespace "receiver" $ withRunInIO $ \rio -> WS.runClient host port "/api/websocket" $ \conn -> rio $ do liftIO $ handshake conn token subscribe bus conn ents liftIO $ atomically $ writeTVar (busConn bus) (Just conn) logLocM InfoS "connected" -- Unpublish on exit so the writer blocks and the backlog survives the outage. receiveLoop bus conn `onException` liftIO (atomically (writeTVar (busConn bus) Nothing)) handshake :: WS.Connection -> String -> IO () handshake conn token = do required <- receiveJSON conn expectType "auth_required" required WS.sendTextData conn $ encode $ object [ "type" .= ("auth" :: T.Text) , "access_token" .= token ] ok <- receiveJSON conn expectType "auth_ok" ok expectType :: T.Text -> Value -> IO () expectType expected msg = case msg ^? key "type" . _String of Just t | t == expected -> pure () _ -> throw (Fatal $ "expected " <> expected <> ", got: " <> T.pack (show msg)) isTriggerEvent :: Value -> Bool isTriggerEvent v = v ^? key "type" . _String == Just "event" subscribe :: HasCallStack => KatipContext m => Bus -> WS.Connection -> S.Set T.Text -> m () subscribe bus conn ents = forM_ (S.toList ents) $ \entityId -> do logLocM InfoS $ ls entityId sid <- liftIO $ generateCallId (busGen bus) liftIO $ WS.sendTextData conn $ encode $ object [ "id" .= sid , "type" .= ("subscribe_trigger" :: T.Text) , "trigger" .= object [ "platform" .= ("state" :: T.Text) , "entity_id" .= entityId ] ] -- | Undecodable messages are skipped: reconnecting cannot fix a decode -- problem, so crashing here would only produce a hot restart loop. -- -- Each read races a one-second timeout: a timeout broadcasts 'Tick' so -- time-based primitives (debounce, rollup, fixed, ...) keep advancing -- even when no state changes arrive. receiveLoop :: (HasCallStack, MonadUnliftIO m, KatipContext m) => Bus -> WS.Connection -> m Void receiveLoop bus conn = forever $ do winner <- race (liftIO $ threadDelay 1_000_000) (liftIO $ WS.receiveData conn) case winner of Left () -> liftIO $ atomically $ writeTChan (busInbound bus) Tick Right msg -> case eitherDecode msg of Left err -> logLocM WarningS $ ls $ "skipping undecodable message: " <> err Right v -> liftIO $ do when (isTriggerEvent v) (recordInbound bus) atomically $ writeTChan (busInbound bus) (Event v) receiveJSON :: WS.Connection -> IO Value receiveJSON conn = do msg <- WS.receiveData conn case eitherDecode msg of Left err -> throw (Fatal $ "Invalid JSON from Home Assistant: " <> T.pack err) Right x -> pure x sendWithId :: (MonadIO m, KatipContext m) => Bus -> WS.Connection -> Service -> RateLimited m () sendWithId bus conn svc = katipAddNamespace "connection" $ do callId <- liftIO $ generateCallId (busGen bus) let textData = encode $ encodeService callId svc logFM DebugS (ls textData) liftIO $ recordOutbound bus liftIO $ WS.sendTextData conn textData writerAction :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> m Void writerAction rateLimiter bus = forever $ do (request, svc) <- liftIO $ atomically $ readTChan (busOutbound bus) katipAddContext (sl "traceId" (toText (requestTraceId request))) $ katipAddNamespace (Namespace [requestHandler request]) $ dispatchService rateLimiter bus request svc -- | Sends the service call, or logs and drops it when its handler is disabled. dispatchService :: (MonadIO m, KatipContext m, MonadCatch m) => RateLimiter -> Bus -> Request -> Service -> m () dispatchService rateLimiter bus request svc = do enabled <- isEnabled (busFlags bus) (requestHandler request) let logPrefix = if enabled then "Calling: " else "Skipping: " logFM InfoS (ls $ logPrefix <> show svc) when enabled $ do conn <- liftIO $ atomically $ readTVar (busConn bus) >>= maybe retry pure runRateLimited rateLimiter $ sendWithId bus conn svc encodeService :: Int -> Service -> Value encodeService callId Service{..} = object $ [ "id" .= callId , "type" .= ("call_service" :: T.Text) , "domain" .= serviceDomain , "service" .= serviceName , "target" .= targetObject serviceTarget ] <> maybe [] (\d -> ["service_data" .= d]) serviceData -- | A single target encodes as a scalar; multiple encode as a list. Empty -- lists are omitted so Home Assistant receives only populated keys. targetObject :: [Target] -> Value targetObject targets = object $ entityPart <> areaPart where entityPart = emit "entity_id" [e | EntityId e <- targets] areaPart = emit "area_id" [a | AreaId a <- targets] emit _ [] = [] emit k [x] = [k .= x] emit k many = [k .= many]