This service is responsible for dispensing chocolate when asked. It makes calls to the Servo Service (for the dispenser Servo) to push and pull the rack controlled by a servo connected to a gear.
# Constants
Create_constant DURATION_DISPENSE as 1000 # milliseconds
Create_constant POSITION_OUT as 40 # out of 180
Create_constant POSITION_IN as 165 # out of 180
Create_constant DISPENSER_SPEED as 180 # out of 255
# Variables
Declare CurrentState as State
Declare DeferralQueue as DeferQueue_t
# Pushes the rack forward to dispense a chocolate
Function StartGoingForward:
Post_to DispenserServo ES_MOVE_TO with parameter POSITION_IN
Start_timer DispenserServiceTimer with duration DURATION_DISPENSE
Endfunction
# Retracts the rack to load a new chocolate
Function StartGoingBackward:
Post_to DispenserServo ES_MOVE_TO with parameter POSITION_OUT
Start_timer DispenserServiceTimer with duration DURATION_DISPENSE
Endfunction
Function InitDispenserService:
Set CurrentState to InitDispenserState
Call Initialize(DeferralQueue)
Post_to DispenserServo ES_SET_SPEED with parameter DISPENSER_SPEED
Post_to DispenserService ES_INIT
Endfunction
Function RunDispenserService(event):
Instantiate NextState to CurrentState
Switch CurrentState:
case InitDispenserState:
If type of event is ES_INIT:
Set NextState to NotDispensing
Post_to DispenserServo ES_MOVE_TO with parameter POSITION_OUT
Endif
case NotDispensing:
If type of event is ES_DISPENSE:
Call StartGoingForward
Set NextState to DispensingForward
Endif
case DispensingForward:
If type of event is ES_DISPENSE:
Add event to DeferralQueue
ElseIf Type of event is ES_TIMEOUT And parameter of event is DispenserServiceTimer:
Call StartGoingBackward
Set NextState to DispensingBackward
Endif
case DispensingBackward:
If type of event is ES_DISPENSE:
Add event to DeferralQueue
ElseIf type of event is ES_TIMEOUT And parameter of event is DispenserServiceTimer:
Set NextState to NotDispensing
Call RecallEvents(DeferralQueue)
Endif
Endswitch
Set CurrentState to NextState
Endfunction