Autonomy Software C++ 24.5.1
Welcome to the Autonomy Software repository of the Mars Rover Design Team (MRDT) at Missouri University of Science and Technology (Missouri S&T)! API reference contains the source code and other resources for the development of the autonomy software for our Mars rover. The Autonomy Software project aims to compete in the University Rover Challenge (URC) by demonstrating advanced autonomous capabilities and robust navigation algorithms.
Loading...
Searching...
No Matches
statemachine::VerifyingObjectState Class Reference

The VerifyingObjectState class implements the Verifying Object state for the Autonomy State Machine. More...

#include <VerifyingObjectState.h>

Inheritance diagram for statemachine::VerifyingObjectState:
Collaboration diagram for statemachine::VerifyingObjectState:

Public Member Functions

 VerifyingObjectState ()
 Accessor for the State private member. Returns the state as a string.
 
void Run () override
 Run the state machine. Returns the next state.
 
States TriggerEvent (Event eEvent) override
 Trigger an event in the state machine. Returns the next state.
 
- Public Member Functions inherited from statemachine::State
 State (States eState)
 Construct a new State object.
 
virtual ~State ()=default
 Destroy the State object.
 
States GetState () const
 Accessor for the State private member.
 
virtual std::string ToString () const
 Accessor for the State private member. Returns the state as a string.
 
virtual bool operator== (const State &other) const
 Checks to see if the current state is equal to the passed state.
 
virtual bool operator!= (const State &other) const
 Checks to see if the current state is not equal to the passed state.
 

Protected Member Functions

void Start () override
 This method is called when the state is first started. It is used to initialize the state.
 
void Exit () override
 This method is called when the state is exited. It is used to clean up the state.
 

Private Attributes

bool m_bInitialized
 
geoops::Waypoint m_stGoalWaypoint
 
objectdetectutils::Object m_stBestObject
 
std::vector< std::shared_ptr< ObjectDetector > > m_vObjectDetectors
 
std::chrono::system_clock::time_point m_tmObjectVerificationStartTime
 
std::chrono::system_clock::time_point m_tmObjectLastSeenTime
 
std::chrono::system_clock::time_point m_tmLastRunTime
 
double m_dTotalValidTime
 

Detailed Description

The VerifyingObjectState class implements the Verifying Object state for the Autonomy State Machine.

Author
Sam Hajdukiewicz (saman.nosp@m.thah.nosp@m.ajduk.nosp@m.iewi.nosp@m.cz@gm.nosp@m.ail..nosp@m.com)
Date
2024-01-17

Constructor & Destructor Documentation

◆ VerifyingObjectState()

statemachine::VerifyingObjectState::VerifyingObjectState ( )

Accessor for the State private member. Returns the state as a string.

Returns
std::string - The current state as a string.
Author
Eli Byrd (edbgk.nosp@m.k@ms.nosp@m.t.edu)
Date
2024-01-17
74 : State(States::eVerifyingObject)
75 {
76 LOG_INFO(logging::g_qConsoleLogger, "Entering State: {}", ToString());
77
78 m_bInitialized = false;
79
80 if (!m_bInitialized)
81 {
82 Start();
83 m_bInitialized = true;
84 }
85 }
virtual std::string ToString() const
Accessor for the State private member. Returns the state as a string.
Definition State.hpp:202
State(States eState)
Construct a new State object.
Definition State.hpp:145
void Start() override
This method is called when the state is first started. It is used to initialize the state.
Definition VerifyingObjectState.cpp:34
Here is the call graph for this function:

Member Function Documentation

◆ Start()

void statemachine::VerifyingObjectState::Start ( )
overrideprotectedvirtual

This method is called when the state is first started. It is used to initialize the state.

Author
Sam Hajdukiewicz (saman.nosp@m.thah.nosp@m.ajduk.nosp@m.iewi.nosp@m.cz@gm.nosp@m.ail..nosp@m.com)
Date
2024-01-17

Reimplemented from statemachine::State.

35 {
36 // Schedule the next run of the state's logic
37 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Scheduling next run of state logic.");
38
39 // Initialize member variables.
40 m_stGoalWaypoint = globals::g_pWaypointHandler->PeekNextWaypoint();
41 m_tmObjectVerificationStartTime = std::chrono::system_clock::now();
42 m_tmObjectLastSeenTime = std::chrono::system_clock::now();
43
44 // Initialize time-based hit tracking
45 m_tmLastRunTime = std::chrono::system_clock::now();
46 m_dTotalValidTime = 0.0;
47
48 // Get object detectors.
49 m_vObjectDetectors = {globals::g_pObjectDetectionHandler->GetObjectDetector(ObjectDetectionHandler::ObjectDetectors::eHeadMainCam),
50 globals::g_pObjectDetectionHandler->GetObjectDetector(ObjectDetectionHandler::ObjectDetectors::eRearCam)};
51 }
std::shared_ptr< ObjectDetector > GetObjectDetector(ObjectDetectors eDetectorName)
Accessor for ObjectDetector detectors.
Definition ObjectDetectionHandler.cpp:153
const geoops::Waypoint PeekNextWaypoint()
Returns an immutable reference to the geoops::Waypoint struct at the front of the list without removi...
Definition WaypointHandler.cpp:540
Here is the call graph for this function:
Here is the caller graph for this function:

◆ Exit()

void statemachine::VerifyingObjectState::Exit ( )
overrideprotectedvirtual

This method is called when the state is exited. It is used to clean up the state.

Author
Sam Hajdukiewicz (saman.nosp@m.thah.nosp@m.ajduk.nosp@m.iewi.nosp@m.cz@gm.nosp@m.ail..nosp@m.com)
Date
2024-01-17

Reimplemented from statemachine::State.

61 {
62 // Clean up the state before exiting
63 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Exiting state.");
64 }
Here is the caller graph for this function:

◆ Run()

void statemachine::VerifyingObjectState::Run ( )
overridevirtual

Run the state machine. Returns the next state.

Author
Sam Hajdukiewicz (saman.nosp@m.thah.nosp@m.ajduk.nosp@m.iewi.nosp@m.cz@gm.nosp@m.ail..nosp@m.com)
Date
2024-01-17

Implements statemachine::State.

94 {
95 LOG_DEBUG(logging::g_qSharedLogger, "VerifyingObjectState: Running state-specific behavior.");
96
97 // IMPORTANT: Ensure the rover is completely stopped to avoid motion blur during verification.
98 globals::g_pDriveBoard->SendStop();
99
100 // 1. Calculate delta time since the last execution of Run()
101 std::chrono::system_clock::time_point tmCurrentTime = std::chrono::system_clock::now();
102 double dDeltaTime = std::chrono::duration_cast<std::chrono::milliseconds>(tmCurrentTime - m_tmLastRunTime).count() / 1000.0;
103 m_tmLastRunTime = tmCurrentTime; // Reset for the next loop
104
105 // 2. Identify target object.
106 objectdetectutils::Object stBestObject;
107 statemachine::IdentifyTargetObject(m_vObjectDetectors, stBestObject, m_stGoalWaypoint.eType);
108
109 // 3. Update Time-Based Hit Rate
110 if (stBestObject.dConfidence > 0.0)
111 {
112 // Add the time that elapsed during this valid frame to our total valid time
113 m_dTotalValidTime += dDeltaTime;
114
115 m_stBestObject = stBestObject; // Save the best object for the snapshot later
116 m_tmObjectLastSeenTime = tmCurrentTime;
117 }
118
119 double dElapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(tmCurrentTime - m_tmObjectVerificationStartTime).count() / 1000.0;
120 double dTimeSinceLastSeen = std::chrono::duration_cast<std::chrono::milliseconds>(tmCurrentTime - m_tmObjectLastSeenTime).count() / 1000.0;
121
122 // 4. Fast-Fail if object is completely lost
123 if (dTimeSinceLastSeen > constants::APPROACH_OBJECT_LOST_BUFFER_TIME)
124 {
125 LOG_WARNING(logging::g_qSharedLogger, "VerifyingObjectState: Lost visual entirely. Fast failing verification.");
126 globals::g_pStateMachineHandler->HandleEvent(Event::eVerifyingFailed);
127 return;
128 }
129
130 // 5. Final Evaluation based on elapsed verification time
131 if (dElapsedTime >= constants::APPROACH_OBJECT_VERIFY_TIME)
132 {
133 // Calculate the percentage of time the object was validly tracked
134 double dTimeHitRate = m_dTotalValidTime / constants::APPROACH_OBJECT_VERIFY_TIME;
135
136 if (dTimeHitRate >= constants::APPROACH_OBJECT_REQUIRED_TIME_HIT_RATE)
137 {
138 LOG_NOTICE(logging::g_qSharedLogger,
139 "VerifyingObjectState: SUCCESS! Confirmed visually for {:.2f}s ({:.2f}% of the required window).",
140 m_dTotalValidTime,
141 dTimeHitRate * 100.0);
142 globals::g_pStateMachineHandler->HandleEvent(Event::eVerifyingComplete);
143 }
144 else
145 {
146 LOG_WARNING(logging::g_qSharedLogger,
147 "VerifyingObjectState: FALSE POSITIVE. Confirmed visually for only {:.2f}s ({:.2f}% of window).",
148 m_dTotalValidTime,
149 dTimeHitRate * 100.0);
150 globals::g_pStateMachineHandler->HandleEvent(Event::eVerifyingFailed);
151 }
152 }
153 }
void SendStop()
Stop the drivetrain of the Rover.
Definition DriveBoard.cpp:246
void HandleEvent(statemachine::Event eEvent, const bool bSaveCurrentState=false)
This method Handles Events that are passed to the State Machine Handler. It will check the current st...
Definition StateMachineHandler.cpp:285
int IdentifyTargetObject(const std::vector< std::shared_ptr< ObjectDetector > > &vObjectDetectors, objectdetectutils::Object &stObjectTarget, const geoops::WaypointType &eDesiredDetectionType=geoops::WaypointType::eUNKNOWN)
Identify a target object in the rover's vision, using Torch detection.
Definition ObjectDetectionChecker.hpp:101
Represents a single detected object.
Definition ObjectDetectionUtility.hpp:73
Here is the call graph for this function:

◆ TriggerEvent()

States statemachine::VerifyingObjectState::TriggerEvent ( Event  eEvent)
overridevirtual

Trigger an event in the state machine. Returns the next state.

Parameters
eEvent- The event to trigger.
Returns
std::shared_ptr<State> - The next state.
Author
Sam Hajdukiewicz (saman.nosp@m.thah.nosp@m.ajduk.nosp@m.iewi.nosp@m.cz@gm.nosp@m.ail..nosp@m.com)
Date
2024-01-17

Implements statemachine::State.

165 {
166 // Create instance variables.
167 States eNextState = States::eVerifyingObject;
168 bool bCompleteStateExit = true;
169
170 switch (eEvent)
171 {
172 case Event::eStart:
173 {
174 // Submit logger message.
175 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Handling Start event.");
176 // Send multimedia command to update state display.
177 globals::g_pMultimediaBoard->SendLightingState(MultimediaBoard::MultimediaBoardLightingState::eAutonomy);
178 break;
179 }
180 case Event::eVerifyingComplete:
181 {
182 // Submit logger message.
183 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Handling Verifying Complete event.");
184 // Send multimedia command to update state display.
185 globals::g_pMultimediaBoard->SendLightingState(MultimediaBoard::MultimediaBoardLightingState::eReachedGoal);
186
187 // Loop through the detectors vector and find which ones UUID matches the winning tag's UUID.
188 // If a match is found, request the snapshot from that detector and save it to disk with a unique filename.
189 cv::Mat cvSnapshot;
190 for (const std::shared_ptr<ObjectDetector>& pObjectDetector : m_vObjectDetectors)
191 {
192 if (pObjectDetector->GetThreadUUID() == m_stBestObject.szDetectorUUID)
193 {
194 std::future<bool> fuFrame = pObjectDetector->RequestLastGoodDetectionOverlayFrame(cvSnapshot);
195 if (!fuFrame.get())
196 {
197 LOG_WARNING(logging::g_qSharedLogger, "VerifyingObjectState: Failed to request detection overlay frame.");
198 }
199 break;
200 }
201 }
202
203 // Check if the snapshot is empty.
204 if (!cvSnapshot.empty())
205 {
206 std::string szLogDir = logging::g_szLoggingOutputPath + "/detections/";
207 if (!std::filesystem::exists(szLogDir))
208 {
209 std::filesystem::create_directories(szLogDir);
210 }
211
212 // Create a unique filename using the current timestamp
213 std::string szTimestamp = timeops::GetTimestamp();
214 std::string szFilename = szLogDir + "object_" + szTimestamp + ".png";
215
216 // Save the image to the disk
217 bool bSuccess = cv::imwrite(szFilename, cvSnapshot);
218
219 if (bSuccess)
220 {
221 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Saved detection snapshot to {}", szFilename);
222 }
223 else
224 {
225 LOG_ERROR(logging::g_qSharedLogger, "VerifyingObjectState: Failed to write snapshot to disk.");
226 }
227 }
228 else
229 {
230 LOG_WARNING(logging::g_qSharedLogger, "VerifyingObjectState: Overlay frame was empty. No snapshot taken.");
231 }
232
233 // Pop old waypoint out of queue.
234 globals::g_pWaypointHandler->PopNextWaypoint();
235 // Clear saved states.
236 globals::g_pStateMachineHandler->ClearSavedStates();
237 // Submit logger message.
238 LOG_NOTICE(logging::g_qSharedLogger, "VerifyingObjectState: Cleared old saved states.");
239 // Change state.
240 eNextState = States::eIdle;
241 break;
242 }
243 case Event::eVerifyingFailed:
244 {
245 // Submit logger message.
246 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Handling Verifying Failed/Object Unseen event.");
247 // Send multimedia command to update state display.
248 globals::g_pMultimediaBoard->SendLightingState(MultimediaBoard::MultimediaBoardLightingState::eAutonomy);
249 // Recall the previous state.
250 eNextState = globals::g_pStateMachineHandler->GetPreviousState();
251 break;
252 }
253 case Event::eStuck:
254 {
255 LOG_INFO(logging::g_qSharedLogger, "NavigatingState: Handling Stuck event.");
256 eNextState = States::eStuck;
257 break;
258 }
259 case Event::eAbort:
260 {
261 // Submit logger message.
262 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Handling Abort event.");
263 // Send multimedia command to update state display.
264 globals::g_pMultimediaBoard->SendLightingState(MultimediaBoard::MultimediaBoardLightingState::eOff);
265 // Change state.
266 eNextState = States::eIdle;
267 break;
268 }
269 default:
270 {
271 LOG_WARNING(logging::g_qSharedLogger, "VerifyingObjectState: Handling unknown event.");
272 eNextState = States::eIdle;
273 break;
274 }
275 }
276
277 if (eNextState != States::eVerifyingObject)
278 {
279 LOG_INFO(logging::g_qSharedLogger, "VerifyingObjectState: Transitioning to {} State.", StateToString(eNextState));
280
281 // Exit the current state
282 if (bCompleteStateExit)
283 {
284 Exit();
285 }
286 }
287
288 return eNextState;
289 }
void SendLightingState(MultimediaBoardLightingState eState)
Sends a predetermined color pattern to board.
Definition MultimediaBoard.cpp:55
void ClearSavedStates()
Clear all saved states.
Definition StateMachineHandler.cpp:311
statemachine::States GetPreviousState() const
Accessor for the Previous State private member.
Definition StateMachineHandler.cpp:358
geoops::Waypoint PopNextWaypoint()
Removes and returns the next waypoint at the front of the list.
Definition WaypointHandler.cpp:500
bool empty() const
void Exit() override
This method is called when the state is exited. It is used to clean up the state.
Definition VerifyingObjectState.cpp:60
bool imwrite(const String &filename, InputArray img, const std::vector< int > &params=std::vector< int >())
std::string StateToString(States eState)
Converts a state object to a string.
Definition State.hpp:85
States
The states that the state machine can be in.
Definition State.hpp:31
std::string GetTimestamp(const std::string &szFormat="%Y%m%d-%H%M%S")
Accessor for getting the current time in a specified format.
Definition TimeOperations.hpp:42
Here is the call graph for this function:

The documentation for this class was generated from the following files: