• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Scala-Robotics-Simulator / PPS-22-srs / #407

27 Aug 2025 05:09PM UTC coverage: 45.055% (+0.2%) from 44.825%
#407

push

github

davidcohenDC
refactor: update event handling logic to use dedicated logic components

0 of 20 new or added lines in 2 files covered. (0.0%)

3 existing lines in 3 files now uncovered.

1116 of 2477 relevant lines covered (45.05%)

6.23 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/main/scala/io/github/srs/controller/ControllerModule.scala
1
package io.github.srs.controller
2

3
import scala.concurrent.duration.{ DurationInt, FiniteDuration, MILLISECONDS }
4
import scala.language.postfixOps
5

6
import cats.effect.std.Queue
7
import cats.effect.{ Clock, IO }
8
import cats.syntax.all.*
9
import io.github.srs.controller.message.RobotProposal
10
import io.github.srs.controller.protocol.Event
11
import io.github.srs.model.*
12
import io.github.srs.model.SimulationConfig.SimulationStatus.{ PAUSED, RUNNING, STOPPED }
13
import io.github.srs.model.entity.dynamicentity.Robot
14
import io.github.srs.model.entity.dynamicentity.behavior.BehaviorContext
15
import io.github.srs.model.entity.dynamicentity.sensor.Sensor.senseAll
16
import io.github.srs.model.logic.*
17
import io.github.srs.utils.EqualityGivenInstances.given_CanEqual_Event_Event
18
import io.github.srs.utils.SimulationDefaults.debugMode
19

20
/**
21
 * Module that defines the controller logic for the Scala Robotics Simulator.
22
 */
23
object ControllerModule:
24

×
25
  /**
26
   * Controller trait that defines the interface for the controller.
27
   *
28
   * @tparam S
29
   *   the type of the state, which must extend [[ModelModule.State]].
30
   */
31
  trait Controller[S <: ModelModule.State]:
32
    /**
×
33
     * Starts the controller with the initial state.
34
     *
35
     * @param initialState
36
     *   the initial state of the simulation.
37
     */
38
    def start(initialState: S): IO[Unit]
39

40
    /**
41
     * Runs the simulation loop, processing events from the queue and updating the state.
42
     *
43
     * @param s
44
     *   the current state of the simulation.
45
     * @param queue
46
     *   a concurrent queue that holds events to be processed.
47
     * @return
48
     *   an [[IO]] task that completes when the simulation loop ends.
49
     */
50
    def simulationLoop(s: S, queue: Queue[IO, Event]): IO[Unit]
51

52
  end Controller
53

54
  /**
55
   * Provider trait that defines the interface for providing a controller.
56
   *
57
   * @tparam S
58
   *   the type of the state, which must extend [[ModelModule.State]].
59
   */
60
  trait Provider[S <: ModelModule.State]:
61
    val controller: Controller[S]
62

63
  /**
64
   * Defines the dependencies required by the controller module. In particular, it requires a
65
   * [[io.github.srs.view.ViewModule.Provider]] and a [[io.github.srs.model.ModelModule.Provider]].
66
   */
67
  type Requirements[S <: ModelModule.State] =
68
    io.github.srs.view.ViewModule.Provider[S] & io.github.srs.model.ModelModule.Provider[S]
69

70
  /**
71
   * Component trait that defines the interface for creating a controller.
72
   *
73
   * @tparam S
74
   *   the type of the simulation state, which must extend [[ModelModule.State]].
75
   */
76
  trait Component[S <: ModelModule.State]:
77
    context: Requirements[S] =>
×
78

79
    object Controller:
80

×
81
      /**
82
       * Creates a controller instance.
83
       *
84
       * @return
85
       *   a [[Controller]] instance.
86
       */
87
      def apply()(using bundle: LogicsBundle[S]): Controller[S] = new ControllerImpl
88

×
89
      /**
90
       * Private controller implementation that delegates the simulation loop to the provided model and view.
91
       */
92
      private class ControllerImpl(using bundle: LogicsBundle[S]) extends Controller[S]:
93

×
94
        /**
95
         * Starts the controller with the initial state.
96
         * @param initialState
97
         *   the initial state of the simulation.
98
         * @return
99
         *   an [[IO]] task that completes when the controller is started.
100
         */
101
        override def start(initialState: S): IO[Unit] =
102
          for
×
103
            queueSim <- Queue.unbounded[IO, Event]
×
104
            _ <- context.view.init(queueSim)
×
105
            _ <- runBehavior(queueSim, initialState)
106
            _ <- simulationLoop(initialState, queueSim)
107
          yield ()
108

×
109
        /**
110
         * Runs the simulation loop, processing events from the queue and updating the state.
111
         * @param s
112
         *   the current state of the simulation.
113
         * @param queue
114
         *   a concurrent queue that holds events to be processed.
115
         * @return
116
         *   an [[IO]] task that completes when the simulation loop ends.
117
         */
118
        override def simulationLoop(s: S, queue: Queue[IO, Event]): IO[Unit] =
119
          def loop(state: S): IO[Unit] =
×
120
            for
×
121
              startTime <- Clock[IO].realTime.map(_.toMillis)
×
122
              _ <- runBehavior(queue, state).whenA(state.simulationStatus == RUNNING)
×
123
              events <- queue.tryTakeN(Some(50))
×
124
              newState <- handleEvents(state, events)
125
              _ <- context.view.render(newState)
126
              nextState <- nextStep(newState, startTime)
127
              endTime <- Clock[IO].realTime.map(_.toMillis)
128
              _ <- if debugMode then IO.println(s"Simulation loop took ${endTime - startTime} ms") else IO.unit
129
              _ <- if stopCondition(nextState) then IO.unit else loop(nextState)
130
            yield ()
131

×
132
          loop(s)
133

×
134
        /**
135
         * Checks if the simulation should stop based on the current state.
136
         * @param state
137
         *   the current state of the simulation.
138
         * @return
139
         *   a boolean indicating whether the simulation should stop.
140
         */
141
        private def stopCondition(state: S): Boolean =
142
          state.simulationStatus == STOPPED ||
×
143
            elapsedTimeReached(state.simulationTime, state.elapsedTime)
×
144

×
145
        /**
146
         * Checks if the elapsed time has reached the maximum simulation time.
147
         * @param simulationTime
148
         *   the maximum simulation time, if defined.
149
         * @param elapsedTime
150
         *   the elapsed time since the simulation started.
151
         * @return
152
         *   a boolean indicating whether the elapsed time has reached the maximum simulation time.
153
         */
154
        private def elapsedTimeReached(simulationTime: Option[FiniteDuration], elapsedTime: FiniteDuration): Boolean =
155
          simulationTime.exists(max => elapsedTime >= max)
×
156

×
157
        /**
158
         * Processes the next step in the simulation based on the current state and start time.
159
         * @param state
160
         *   the current state of the simulation.
161
         * @param startTime
162
         *   the start time of the current simulation step in milliseconds.
163
         * @return
164
         *   the next state of the simulation wrapped in an [[IO]] task.
165
         */
166
        private def nextStep(state: S, startTime: Long): IO[S] =
167
          state.simulationStatus match
×
168
            case RUNNING =>
×
169
              tickEvents(startTime, state.simulationSpeed.tickSpeed, state)
×
170

×
171
            case PAUSED =>
172
              IO.sleep(50.millis).as(state)
×
173

×
174
            case STOPPED =>
175
              IO.pure(state)
×
176

×
177
        /**
178
         * Runs the behavior of all robots in the environment and collects their action proposals.
179
         * @param queue
180
         *   the queue to which the proposals will be offered through the [[Event.RobotActionProposals]] event.
181
         * @param state
182
         *   the current state of the simulation.
183
         * @return
184
         *   an [[IO]] task that completes when the behavior has been run.
185
         */
186
        private def runBehavior(queue: Queue[IO, Event], state: S): IO[Unit] =
187
          for
×
188
            proposals <- state.environment.entities.collect { case robot: Robot => robot }.toList.parTraverse { robot =>
×
189
              for
×
190
                sensorReadings <- robot.senseAll[IO](state.environment)
191
                ctx = BehaviorContext(sensorReadings, state.simulationRNG)
192
                (action, rng) = robot.behavior.run[IO](ctx)
193
                _ <- queue.offer(Event.Random(rng))
194
              yield RobotProposal(robot, action)
195
            }
196
            _ <- queue.offer(Event.RobotActionProposals(proposals))
×
197
          yield ()
198

×
199
        /**
200
         * Processes tick events, adjusting the tick speed based on the elapsed time since the last tick.
201
         * @param start
202
         *   the start time of the current tick in milliseconds.
203
         * @param tickSpeed
204
         *   the speed of the tick in [[FiniteDuration]].
205
         * @param state
206
         *   the current state of the simulation.
207
         * @return
208
         *   the next state of the simulation wrapped in an [[IO]] task.
209
         */
210
        private def tickEvents(start: Long, tickSpeed: FiniteDuration, state: S): IO[S] =
211
          for
×
212
            now <- Clock[IO].realTime.map(_.toMillis)
×
213
            timeToNextTick = tickSpeed.toMillis - (now - start)
×
214
            adjustedTickSpeed = if timeToNextTick > 0 then timeToNextTick else 0L
215
            sleepTime = FiniteDuration(adjustedTickSpeed, MILLISECONDS)
216
            _ <- IO.sleep(sleepTime)
×
217
            tick <- handleEvent(state, Event.Tick(tickSpeed))
218
          yield tick
219

×
220
        /**
221
         * Handles a sequence of events, processing them in the order they were received.
222
         * @param state
223
         *   the current state of the simulation.
224
         * @param events
225
         *   the sequence of events to be processed.
226
         * @return
227
         *   the final state of the simulation after processing all events, wrapped in an [[IO]] task.
228
         */
229
        private def handleEvents(state: S, events: Seq[Event]): IO[S] =
230
          for finalState <- events.foldLeft(IO.pure(state)) { (taskState, event) =>
×
231
              for
×
232
                currentState <- taskState
233
                newState <- handleEvent(currentState, event)
234
              yield newState
235
            }
236
          yield finalState
×
237

×
238
        /**
239
         * Handles a single event and updates the state accordingly.
240
         * @param state
241
         *   the current state of the simulation.
242
         * @param event
243
         *   the event to be processed.
244
         * @return
245
         *   the updated state of the simulation after processing the event, wrapped in an [[IO]] task.
246
         */
247
        private def handleEvent(state: S, event: Event): IO[S] =
248
          event match
×
NEW
249
            case Event.Tick(deltaTime) =>
×
NEW
250
              context.model.update(state)(using s => bundle.tickLogic.tick(s, deltaTime))
×
NEW
251
            case Event.TickSpeed(speed) =>
×
NEW
252
              context.model.update(state)(using s => bundle.tickLogic.tickSpeed(s, speed))
×
NEW
253
            case Event.Random(rng) =>
×
NEW
254
              context.model.update(state)(using s => bundle.randomLogic.random(s, rng))
×
NEW
255
            case Event.Pause =>
×
NEW
256
              context.model.update(state)(using s => bundle.pauseLogic.pause(s))
×
NEW
257
            case Event.Resume =>
×
NEW
258
              context.model.update(state)(using s => bundle.resumeLogic.resume(s))
×
NEW
259
            case Event.Stop =>
×
NEW
260
              context.model.update(state)(using s => bundle.stopLogic.stop(s))
×
NEW
261
            case Event.RobotActionProposals(proposals) =>
×
NEW
262
              context.model.update(state)(using s => bundle.robotActionsLogic.handleRobotActionsProposals(s, proposals))
×
UNCOV
263

×
264
      end ControllerImpl
265

266
    end Controller
267

268
  end Component
269

270
  /**
271
   * Interface trait that combines the provider and component traits for the controller module.
272
   *
273
   * @tparam S
274
   *   the type of the simulation state, which must extend [[ModelModule.State]].
275
   */
276
  trait Interface[S <: ModelModule.State] extends Provider[S] with Component[S]:
277
    self: Requirements[S] =>
278
end ControllerModule
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc