packages feed

zwirn-0.2.2.0: src/zwirn-lang/Zwirn/Stream/Target.hs

{-# LANGUAGE DeriveFunctor #-}

module Zwirn.Stream.Target where

import qualified Data.Map as Map
import Data.Text (Text)
import qualified Network.Socket as N

type RemoteAddress = N.SockAddr

type TargetName = Text

data Targeted a
  = Targeted
  { targets :: [TargetName],
    tValue :: a
  }
  deriving (Functor)

data Target = Target
  { tOSCPath :: Text,
    tBusOSCPath :: Text,
    tAddress :: RemoteAddress,
    tBusAddress :: Maybe RemoteAddress
  }

type TargetMap = Map.Map TargetName Target

data TargetConfig = TargetConfig
  { targetConfigName :: Text,
    targetConfigOSCPath :: Text,
    targetConfigBusOSCPath :: Text,
    targetConfigAddress :: String,
    targetConfigPort :: Int,
    targetConfigBusPort :: Maybe Int
  }

resolve :: String -> Int -> IO N.AddrInfo
resolve host port = do
  let hints = N.defaultHints {N.addrSocketType = N.Stream}
  addr : _ <- N.getAddrInfo (Just hints) (Just host) (Just $ show port)
  return addr

getTarget :: TargetConfig -> IO (Text, Target)
getTarget config = do
  let target_address = targetConfigAddress config
      target_port = targetConfigPort config
      target_bus_port = targetConfigBusPort config
  remote <- resolve target_address target_port
  remoteBus <- mapM (resolve target_address) target_bus_port
  return (targetConfigName config, Target (targetConfigOSCPath config) (targetConfigBusOSCPath config) (N.addrAddress remote) (N.addrAddress <$> remoteBus))

getTargetMap :: [TargetConfig] -> IO TargetMap
getTargetMap confs = Map.fromList <$> mapM getTarget confs