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

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

22 Aug 2025 03:44PM UTC coverage: 57.73% (+0.6%) from 57.15%
#350

push

github

srs-mate
refactor: update robot action logic to use default max retries and binary search duration threshold

1 of 3 new or added lines in 2 files covered. (33.33%)

85 existing lines in 10 files now uncovered.

1109 of 1921 relevant lines covered (57.73%)

8.09 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.UpdateLogic.*
14
import io.github.srs.model.entity.dynamicentity.Robot
15
import io.github.srs.model.entity.dynamicentity.sensor.Sensor.senseAll
16
import io.github.srs.model.logic.*
17
import io.github.srs.utils.SimulationDefaults.debugMode
18
import io.github.srs.utils.EqualityGivenInstances.given_CanEqual_Event_Event
19

20
/**
21
 * Module that defines the controller logic for the Scala Robotics Simulator.
22
 */
23
object ControllerModule:
UNCOV
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]:
UNCOV
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]:
UNCOV
77
    context: Requirements[S] =>
×
78

79
    object Controller:
UNCOV
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
UNCOV
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]:
UNCOV
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 ()
UNCOV
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] =
UNCOV
119
          def loop(state: S): IO[Unit] =
×
UNCOV
120
            for
×
UNCOV
121
              startTime <- Clock[IO].realTime.map(_.toMillis)
×
UNCOV
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)
UNCOV
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 =
UNCOV
155
          simulationTime.exists(max => elapsedTime >= max)
×
UNCOV
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
×
UNCOV
168
            case RUNNING =>
×
UNCOV
169
              tickEvents(startTime, state.simulationSpeed.tickSpeed, state)
×
UNCOV
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
                action = robot.behavior.run(sensorReadings)
192
              yield RobotProposal(robot, action)
193
            }
UNCOV
194
            _ <- queue.offer(Event.RobotActionProposals(proposals))
×
195
          yield ()
UNCOV
196

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

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

×
236
        /**
237
         * Handles a single event and updates the state accordingly.
238
         * @param state
239
         *   the current state of the simulation.
240
         * @param event
241
         *   the event to be processed.
242
         * @return
243
         *   the updated state of the simulation after processing the event, wrapped in an [[IO]] task.
244
         */
245
        private def handleEvent(state: S, event: Event): IO[S] =
UNCOV
246
          event match
×
UNCOV
247
            case Event.Tick(deltaTime) => context.model.tick(state, deltaTime)
×
UNCOV
248
            case Event.TickSpeed(speed) => context.model.tickSpeed(state, speed)
×
UNCOV
249
            case Event.Random(rng) => context.model.random(state, rng)
×
UNCOV
250
            case Event.Pause => context.model.pause(state)
×
UNCOV
251
            case Event.Resume => context.model.resume(state)
×
UNCOV
252
            case Event.Stop => context.model.stop(state)
×
UNCOV
253
            case Event.RobotActionProposals(proposals) => context.model.handleRobotActionsProposals(state, proposals)
×
UNCOV
254

×
255
      end ControllerImpl
256

257
    end Controller
258

259
  end Component
260

261
  /**
262
   * Interface trait that combines the provider and component traits for the controller module.
263
   *
264
   * @tparam S
265
   *   the type of the simulation state, which must extend [[ModelModule.State]].
266
   */
267
  trait Interface[S <: ModelModule.State] extends Provider[S] with Component[S]:
268
    self: Requirements[S] =>
269
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