packages feed

zwirn-0.2.3.1: src/zwirn-stream/Zwirn/Stream/Target.hs

module Zwirn.Stream.Target where

import qualified Data.Map as Map
import Data.Text (Text)
import qualified Network.Socket as N
import Zwirn.Language.Play (TargetName)

type RemoteAddress = N.SockAddr

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