{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RebindableSyntax #-}
{-# LANGUAGE TypeApplications #-}
module Copilot.Arduino.Library.Random (
randomSeed,
randomSeedPin,
RandomSeed,
RandomInput,
random,
randomR,
) where
import Copilot.Arduino hiding (show)
import Copilot.Arduino.Internals
import Control.Monad.Writer
import Data.Proxy
import Prelude ()
import qualified Prelude
randomSeed :: RandomSeed
randomSeed = RandomSeed
data RandomSeed = RandomSeed
instance Output RandomSeed (Event () (Stream Word8)) where
RandomSeed =: e = randomSeedWith e
instance Output RandomSeed (Event () (Stream ADC)) where
RandomSeed =: e = randomSeedWith e
randomSeedWith :: Typed a => Event p (Stream a) -> Sketch ()
randomSeedWith (Event n c) = do
(f, triggername) <- defineTriggerAlias "randomSeed" mempty
tell [(go triggername, \_ -> f)]
where
go triggername tl =
let c' = addTriggerLimit tl c
in trigger triggername c' [arg n]
randomSeedPin :: IsAnalogInputPin t => Pin t -> Sketch ()
randomSeedPin p = do
seed <- input p :: Sketch (Behavior ADC)
randomSeed =: seed
data RandomInput = RandomInput Word32 Word32
random :: Word32 -> RandomInput
random hi = RandomInput 0 hi
randomR :: (Word32, Word32) -> RandomInput
randomR (lo, hi) = RandomInput lo hi
instance Input RandomInput Word32 where
input' (RandomInput lo hi) interpretvalues = do
i <- getUniqueId "random"
let varname = uniqueName "randomval" i
let word32 = showCType (Proxy @Word32)
mkInput $ InputSource
{ setupInput = []
, defineVar = mkCChunk
[ CLine $ word32 <> " " <> varname <> ";"
]
, inputPinmode = mempty
, readInput = mkCChunk
[ CLine $ varname <> " = random"
<> "("
<> Prelude.show lo
<> ", "
<> Prelude.show hi
<> ");"]
, inputStream = extern varname interpretvalues'
}
where
interpretvalues'
| null interpretvalues = Nothing
| otherwise = Just interpretvalues