00001 /* 00002 * Software License Agreement (Apache License) 00003 * 00004 * Copyright (c) 2016 Shaun Edwards 00005 * 00006 * Licensed under the Apache License, Version 2.0 (the "License"); 00007 * you may not use this file except in compliance with the License. 00008 * You may obtain a copy of the License at 00009 * 00010 * http://www.apache.org/licenses/LICENSE-2.0 00011 * 00012 * Unless required by applicable law or agreed to in writing, software 00013 * distributed under the License is distributed on an "AS IS" BASIS, 00014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00015 * See the License for the specific language governing permissions and 00016 * limitations under the License. 00017 */ 00018 00019 00020 #include "packml_sm/state.h" 00021 #include "packml_sm/events.h" 00022 00023 #include <functional> 00024 00025 namespace packml_sm 00026 { 00027 00028 void PackmlState::onEntry(QEvent *e) 00029 { 00030 ROS_DEBUG_STREAM("Entering state: " << name_.toStdString() << "(" << state_ <<")"); 00031 emit stateEntered(static_cast<int>(state_), name_); 00032 enter_time_ = ros::Time::now(); 00033 } 00034 00035 00036 void PackmlState::onExit(QEvent *e) 00037 { 00038 00039 ROS_DEBUG_STREAM("Exiting state: " << name_.toStdString() << "(" << state_ << ")"); 00040 exit_time_ = ros::Time::now(); 00041 cummulative_time_ = cummulative_time_ + (exit_time_ - enter_time_); 00042 ROS_DEBUG_STREAM("Updating cummulative time, for state: " << name_.toStdString() << "(" 00043 << state_ << ") to: " << cummulative_time_.toSec()); 00044 } 00045 00046 void ActingState::onEntry(QEvent *e) 00047 { 00048 PackmlState::onEntry(e); 00049 ROS_DEBUG_STREAM("Starting thread for state operation"); 00050 function_state_ = QtConcurrent::run(std::bind(&ActingState::operation, this)); 00051 } 00052 00053 void ActingState::onExit(QEvent *e) 00054 { 00055 if (function_state_.isRunning()) 00056 { 00057 ROS_DEBUG_STREAM("State exit triggered early, waitiing for state operation to complete"); 00058 } 00059 function_state_.waitForFinished(); 00060 PackmlState::onExit(e); 00061 } 00062 00063 00064 void ActingState::operation() 00065 { 00066 QEvent* sc; 00067 if( function_ ) 00068 { 00069 ROS_DEBUG_STREAM("Executing operational function in acting state"); 00070 int error_code = function_(); 00071 if( 0 == error_code ) 00072 { 00073 sc = new StateCompleteEvent(); 00074 } 00075 else 00076 { 00077 ROS_ERROR_STREAM("Operational function returned error code: " << error_code); 00078 sc = new ErrorEvent(error_code); 00079 } 00080 } 00081 else 00082 { 00083 ROS_DEBUG_STREAM("Default operation, delaying " << delay_ms << " ms"); 00084 ros::WallDuration(delay_ms/1000.0).sleep(); 00085 ROS_DEBUG_STREAM("Operation delay complete"); 00086 sc = new StateCompleteEvent(); 00087 } 00088 machine()->postEvent(sc); 00089 } 00090 00091 }//packml_sm