/
Main.hs
333 lines (273 loc) · 8.62 KB
/
Main.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
{-# LANGUAGE Arrows, MultiWayIf #-}
-- based on example in https://wiki.haskell.org/Yampa/reactimate
import Control.Monad
import Data.IORef
import Data.Time.Clock
import FRP.Yampa
import FRP.Yampa.Geometry
import Control.Arrow
import Data.Map.Strict ((!))
import qualified Data.Map.Strict as Map
import System.IO
import System.IO.Error
import System.Posix.Signals
import System.Linux.Input.Device
import qualified System.Linux.Input.Event as EvDev
import System.Timeout
import System.Hardware.WiringPi
import Control.Exception
import Control.Concurrent
import Control.Concurrent.Chan
import Debug.Trace
data Inputs = Inputs {
iNewUpdate :: Event (),
iDisconnected :: Event (),
iJoystick :: Event JoystickState,
iButton :: Event ButtonState
} deriving (Show)
data JoystickState = Up
| Down
| Middle deriving (Eq, Show)
data ButtonState = ButtonState Button Bool deriving (Eq, Show)
data Button = Trigger
| Shoulder
| Joystick
| DUp
| DDown
| DLeft
| DRight deriving (Eq, Show, Ord)
data MaybeRawEvents = InputDisconnected
| RawInput EvDev.Event
defaultInputs = Inputs {
iNewUpdate = NoEvent,
iDisconnected = NoEvent,
iJoystick = NoEvent,
iButton = NoEvent
}
newInputs = defaultInputs {
iNewUpdate = Event ()
}
resetInputs = defaultInputs {
iDisconnected = Event ()
}
data Outputs = Outputs {
oPrintBuffer :: Event [Char],
oPWMOutput :: !PwmValue
} deriving (Show)
defaultOutputs = Outputs {
oPrintBuffer = NoEvent,
oPWMOutput = 0
}
---
pwmPin = Gpio 18
statusLedPin = Gpio 12
pwmClock = 94
pwmRange = 4096 :: PwmValue
---
rampedThrottleP = 0.70
--throttleStepPerSecond = 0.20
---
cruisingSpeedTarget = 0.35
fastSpeedTarget = 0.45
---
maxOutputToEsc = 0.5
minOutputToEsc = 0.05
statusLedOn :: IO ()
statusLedOn = digitalWrite statusLedPin HIGH
statusLedOff :: IO ()
statusLedOff = digitalWrite statusLedPin LOW
main :: IO ()
main = do
t <- getCurrentTime
timeRef <- newIORef t
inputsChan <- initInputsThread
reactimate initialize (sense timeRef inputsChan) actuate outputsSignal
initialize :: IO Inputs
initialize = do
putStrLn "Hello!"
let handler = do
pwmWrite pwmPin 0
statusLedOff
raiseSignal sigTERM
installHandler keyboardSignal (Catch handler) Nothing
putStrLn "Initializing PWM..."
pinMode pwmPin PWM_OUTPUT
pullUpDnControl statusLedPin PUD_UP
pinMode statusLedPin OUTPUT
pwmSetMode PWM_MODE_MS
pwmSetClock pwmClock
pwmSetRange pwmRange
putStrLn "Initialized."
return (defaultInputs)
initInputsThread :: IO (Chan (MaybeRawEvents))
initInputsThread = do
inputsChan <- newChan
let
loop = do
statusLedOff
maybeHandle <- try $ openFile "/dev/input/event0" ReadMode
case maybeHandle of
Right handle -> do
traceIO "Connected to event interface."
statusLedOn
forever $ do
maybeEvent <- try $ EvDev.hReadEvent handle
case maybeEvent of
Right (Just event) -> do
writeChan inputsChan (RawInput event)
Left e -> do
return (isDoesNotExistError e) -- removes type ambig.
writeChan inputsChan InputDisconnected
loop
threadDelay (1000 * 20)
return ()
Left e -> do
return (isDoesNotExistError e) -- removes type ambig.
writeChan inputsChan InputDisconnected
threadDelay (1000 * 20)
return ()
in (forkIO . forever) $ loop
return (inputsChan)
sense :: IORef UTCTime -> Chan (MaybeRawEvents) -> Bool -> IO (Double, Maybe Inputs)
sense timeRef inputsChan _ = do
now <- getCurrentTime
lastTime <- readIORef timeRef
writeIORef timeRef now
let dt = now `diffUTCTime` lastTime
maybeData <- timeout (1000 * 10) $ readChan inputsChan
let
inputs = case maybeData of
Nothing -> defaultInputs
Just maybeRawEvents -> case maybeRawEvents of
InputDisconnected -> resetInputs
RawInput event -> interpretInput event
return (realToFrac dt, Just inputs)
interpretInput :: EvDev.Event -> Inputs
interpretInput (EvDev.AbsEvent _ axis val) = newInputs {
iJoystick =
if axis == abs_hat0x
then Event $ case compare val 0 of
LT -> Up
GT -> Down
EQ -> Middle
else NoEvent
}
where
abs_hat0x = EvDev.AbsAxis 16
abs_hat0y = EvDev.AbsAxis 17
interpretInput (EvDev.KeyEvent _ key state) = newInputs {
iButton = buttonEvent
}
where
map' x y = if key == x
then case state of
EvDev.Depressed -> Event (ButtonState y True)
EvDev.Released -> Event (ButtonState y False)
_ -> NoEvent
else NoEvent
buttonEvent = mergeEvents
[
map' (EvDev.Key 319) Trigger,
map' (EvDev.Key 318) Shoulder,
map' (EvDev.Key 314) Joystick,
map' (EvDev.Key 306) DUp,
map' (EvDev.Key 305) DDown,
map' (EvDev.Key 304) DLeft,
map' (EvDev.Key 307) DRight
]
interpretInput _ = defaultInputs
actuate :: Bool -> Outputs -> IO Bool
actuate _ outputs = do
if isEvent $ oPrintBuffer outputs
then do
putStrLn $ fromEvent $ oPrintBuffer outputs
pwmWrite pwmPin $ oPWMOutput outputs
else return ()
return False
-- note: our esc does not have a programmable break
-- so to "break" means to bring the power down to 0 very quickly
-- by setting the target to a negative value
-- as opposed to slowly bringing the power down in "neutral"
-- by having the target be 0
data ThrottleTargets = Break
| Neutral
| CruisingSpeed
| FastSpeed deriving (Show)
outputsSignal :: SF Inputs Outputs
outputsSignal = proc i -> do
isShoulderDown <- hold False -< isDown Shoulder i
isTriggerDown <- hold False -< isDown Trigger i
isDUpDown <- hold False -< isDown DUp i
isDDownDown <- hold False -< isDown DDown i
isDLeftDown <- hold False -< isDown DLeft i
isDRightDown <- hold False -< isDown DRight i
let userInputMap = Map.fromList
[
(Shoulder, isShoulderDown),
(Trigger, isTriggerDown),
(DUp, isDUpDown),
(DDown, isDDownDown),
(DLeft, isDLeftDown),
(DRight, isDRightDown)
]
-- Normal Mode
gas <-
hold False
<<< (arr $ fmap (== Up))
-< iJoystick i
break <-
hold True
<<< (arr $ fmap (== Down))
-< iJoystick i
let speed =
if | break -> Break
| gas && userInputMap ! Shoulder -> FastSpeed
| gas && userInputMap ! Trigger -> CruisingSpeed
| otherwise -> Neutral
let normalTarget =
case speed of
Break -> (-0.5)
Neutral -> 0.0
CruisingSpeed -> cruisingSpeedTarget
FastSpeed -> fastSpeedTarget
normalOutput <- rampedThrottleSF -< normalTarget
-- Programming Mode
programmingMode <-
accumHoldBy (\acc _ -> not acc) False
-< filterE (== (ButtonState DRight True)) $ iButton i
let programmingOutput =
if | userInputMap ! DUp -> 1.0
| userInputMap ! DLeft -> 0.5
| userInputMap ! DDown -> 0.0
| otherwise -> 0.0
let output =
if | not programmingMode -> normalOutput
| programmingMode -> programmingOutput
| otherwise -> 0.0
actualOutput = id
$ (0.0, 1.0) `rescale` (0.0, 0.7)
$ (\x -> if x < minOutputToEsc then 0.0 else x)
$ clamp (0, maxOutputToEsc)
$ output
printMessageEvent <- repeatedly 0.3 () -< ()
returnA -< Outputs {
oPrintBuffer = printMessageEvent `tag` (show actualOutput),
oPWMOutput = round $ (* (fromIntegral pwmRange))
$ (1.1 + actualOutput) / (20.0 :: Double)
}
where
clamp (mn, mx) = max mn . min mx
rescale (mn, mx) (mn', mx') = (*) ((mx' - mn') / (mx - mn))
isDown button inputs = aux $ iButton inputs
where
aux (Event (ButtonState button' x)) =
if button == button'
then Event x
else NoEvent
aux _ = NoEvent
rampedThrottleSF = proc target -> do
rec
let error = target - position
position <- integral -< (error * rampedThrottleP)
--position <- integral -< (signum error * throttleStepPerSecond)
returnA -< position