diff --git a/docs/images/motion_modes_chicken_head_refused.png b/docs/images/motion_modes_chicken_head_refused.png new file mode 100644 index 0000000..a86700c Binary files /dev/null and b/docs/images/motion_modes_chicken_head_refused.png differ diff --git a/docs/images/motion_modes_demo_running.png b/docs/images/motion_modes_demo_running.png new file mode 100644 index 0000000..7f0eab7 Binary files /dev/null and b/docs/images/motion_modes_demo_running.png differ diff --git a/docs/images/motion_modes_refused_before_start.png b/docs/images/motion_modes_refused_before_start.png new file mode 100644 index 0000000..a629fcd Binary files /dev/null and b/docs/images/motion_modes_refused_before_start.png differ diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 14fa9e0..3e87a56 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -101,6 +101,9 @@ before starting the SDL bridge. | Incision group: left stick up/down | Insert or withdraw the tool along its own axis | | Incision group: right stick up/down | Tilt the tool about the incision point | | Incision group: right stick left/right | Tool roll | +| Chicken head mode: left stick up/down | Tilt the tool about the held tip (the D-pad left/right tilt it too) | +| Chicken head mode: right stick left/right | Tool roll | +| Demo mode: sticks | Nothing: the demo moves the arm (RT / LT still work the tool) | | RT / LT | Close / open the placeholder end effector | | D-pad up/down | Speed: 10, 25, 50 or 100% of 60 deg/s, or of 50 mm/s and 30 deg/s of tilt in the Cartesian and incision groups | | A (hold) | Return to the zero pose (not in the incision group) | @@ -176,6 +179,72 @@ incision. With five joints, the tool can only tilt in the arm's vertical plane. stops rather than pull the tool back: press Y, withdraw the tool in another group, then select the incision group again. +**Chicken head mode** holds the tool tip at one spot while the rest of the arm moves around +it, as a chicken keeps its head still. Press Start first, then tick **Chicken head mode** in +the Motion modes panel (right-hand dock, under Arm setup). The same switch is the +`/arm/chicken_head/set_enabled` service (`std_srvs/SetBool`), and its state is on the latched +`/arm/chicken_head` topic. The arm moves every joint in a straight line to the head spot, at +the current speed level, which takes a few seconds, and then holds it there. The default spot +is 30 cm in front of the base and 55 cm up, with the tool pointing forward (`chicken_head` in +`xbox_teleop.yaml`). Once the panel says *holding*, centre the sticks: the left stick tilts the +tool and the right stick rolls it. The shoulder, elbow and wrist swing as far as the tilt needs, +and in simulation the tip stays within half a millimetre of the spot. + +- The panel refuses, and says why, when teleop is not enabled, when a joint is locked or + switched off (the mode needs J1 to J5), when the tool is inserted through the incision + point, or when the head spot is out of reach of the arm's joint limits. +- The mode ends, and the arm holds where it is, when you untick the box, press B, press Y + (which also selects the next group) or A, stop teleop with Start, or the controller drops + out. +- Something in the way, such as the table or the base, stops the approach. After 1.5 s the + panel says *blocked* and names the joint. A tilt that reaches a joint limit stops there and + names the joint, and the tip stays held. +- The approach moves all five joints at once, so on a real arm try it first at a low speed + with the stop within reach. + +**Demo mode** moves the arm around by itself, slowly and smoothly, to show it off or to look it +over. Press Start first, then tick **Demo mode** in the Motion modes panel. The same switch is the +`/arm/demo/set_enabled` service (`std_srvs/SetBool`), and its state is on the latched `/arm/demo` +topic (`off`, `running`, `stopping` or `unavailable`). Each joint swings about the pose the arm was +in when you ticked the box, at its own pace, so the motion does not repeat for two minutes. The +swing grows over 12 seconds, and when you untick the box it shrinks over as long, which brings the +arm back to exactly the pose it started from (the panel says *returning*). Ticking the box again +while it returns carries on from there. With the settings in `xbox_teleop.yaml` (`demo`), no joint +is commanded to go faster than 7 deg/s or to speed up or slow down by more than 3 deg/s each +second, and the tool tip stays under 8 cm/s. Through the simulated drives the arm follows that path +to within 0.2 degrees. + +![The Motion modes panel while demo mode runs](images/motion_modes_demo_running.png) + +Only one mode runs at a time, and the panel says why a mode is refused. While demo mode runs, +chicken head is refused; before Start has been pressed, demo mode is: + +![Chicken head refused while demo mode runs](images/motion_modes_chicken_head_refused.png) + +![Demo mode refused until Start is pressed, with the Arm setup panel above the Motion modes panel](images/motion_modes_refused_before_start.png) + +- It is not the other two demos. `autoplay:=true` (the self-running demo, above) plays a scripted + controller, presses Start itself and runs only on simulated drives. `demo_mode:=true` sweeps each + joint once to check the TF, also in simulation only. Demo mode needs your Start press and is + checked like any other motion, so it can run on the real arm. +- The sticks do nothing, and D-pad down slows it to half and then a fifth of its pace, including the + start and the return. D-pad up never speeds it up. +- B, Start, Y, A or losing the controller end it at once and hold the arm where it is, as they do + for any motion. Unticking the box is the gentle way out. +- The arm stays 10 degrees clear of its joint limits. A joint that is locked or switched off stays + still, and one with less than 3 degrees of room does too. If a link would reach the table or the + base at the extremes of the swing, the whole swing is made smaller, and if no size fits the panel + says what is in the way and the mode does not start. If a step runs into something anyway, the + mode ends, the arm holds, the controller rumbles and the panel says why until you start it again. +- It is refused, with the reason, until teleop is enabled, while chicken head mode is on (and the + other way round), and while the tool is through the incision point. If you untick it while still + holding a stick, the sticks have to be centred before they move the arm. +- The swing of each joint, its pace, the time to grow and shrink and the speed limit are in the + `demo` section of `xbox_teleop.yaml`. Settings that would let a joint go faster than + `max_speed_deg_s` are refused when teleop starts. +- On the real arm it moves by itself: keep the emergency stop within reach, and press D-pad down + twice before the first run to see it at a fifth of its pace. + ### Joint limits and collision checks The current arm URDF has provisional joint limits, and the collision checks model @@ -224,7 +293,8 @@ again whenever the controller has been left alone for 30 seconds. The arm lifts, draws a square and a vertical line with the tool tip, and tilts the tool about its tip, with the path and a caption in RViz. Touching any button, stick or trigger stops the demo and leaves teleop disabled; press Start to drive the arm yourself. -The demo runs only with simulated drives. +The demo runs only with simulated drives. To see the real arm move around by itself, use +[Demo mode](#how-teleop-behaves) instead. - **Windows:** double-click `scripts\windows-demo.cmd`. It starts Docker Desktop if needed, opens the controller bridge in its own window if Python 3 is installed, diff --git a/waybionic_bringup/rviz/waybionic_unified.rviz b/waybionic_bringup/rviz/waybionic_unified.rviz index ab1ed49..b5dbb6a 100644 --- a/waybionic_bringup/rviz/waybionic_unified.rviz +++ b/waybionic_bringup/rviz/waybionic_unified.rviz @@ -30,6 +30,8 @@ Panels: SyncSource: "" - Class: waybionic_rviz_plugins/SetupPanel Name: SetupPanel + - Class: waybionic_rviz_plugins/MotionModesPanel + Name: MotionModesPanel - Class: waybionic_rviz_plugins/JointControlPanel Name: JointControlPanel - Class: waybionic_rviz_plugins/DiagnosticsPanel @@ -214,6 +216,8 @@ Window Geometry: collapsed: false JointControlPanel: collapsed: false + MotionModesPanel: + collapsed: false SetupPanel: collapsed: false Displays: @@ -221,7 +225,7 @@ Window Geometry: Height: 800 Hide Left Dock: false Hide Right Dock: false - QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002b4fc0200000001fc00000014000002b40000007601000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000005200fffffffb0000000a005600690065007700730100000000ffffffff0000005200fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000005200fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000005200ffffff00000001000001b8000002b4fc0200000003fb000000140053006500740075007000500061006e0065006c0100000014000000970000005200fffffffb00000022004a006f0069006e00740043006f006e00740072006f006c00500061006e0065006c01000000b1000000970000005200fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c010000014e0000017a0000005200ffffff000000030000050000000052fc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002b400000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002b4fc0200000001fc00000014000002b40000004e01000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000002a00fffffffb0000000a005600690065007700730100000000ffffffff0000002a00fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000002a00fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000002a00ffffff00000001000001b8000002b4fc0200000004fb000000140053006500740075007000500061006e0065006c0100000014000000870000002a00fffffffb00000020004d006f00740069006f006e004d006f00640065007300500061006e0065006c01000000a1000000430000002a00fffffffb00000022004a006f0069006e00740043006f006e00740072006f006c00500061006e0065006c01000000ea000000870000002a00fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000177000001510000002a00ffffff000000030000050000000052fc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002b400000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 Selection: collapsed: false Time: diff --git a/waybionic_rviz_plugins/CMakeLists.txt b/waybionic_rviz_plugins/CMakeLists.txt index 9fb1c5e..bf13ad2 100644 --- a/waybionic_rviz_plugins/CMakeLists.txt +++ b/waybionic_rviz_plugins/CMakeLists.txt @@ -31,7 +31,10 @@ add_library(${PROJECT_NAME} SHARED include/waybionic_rviz_plugins/diagnostics_panel.hpp include/waybionic_rviz_plugins/joint_control_model.hpp include/waybionic_rviz_plugins/joint_control_panel.hpp + include/waybionic_rviz_plugins/mode_model.hpp + include/waybionic_rviz_plugins/motion_modes_panel.hpp include/waybionic_rviz_plugins/motion_test_panel.hpp + include/waybionic_rviz_plugins/panel_fit.hpp include/waybionic_rviz_plugins/ros_diagnostics_source.hpp include/waybionic_rviz_plugins/setup_model.hpp include/waybionic_rviz_plugins/setup_panel.hpp @@ -39,6 +42,8 @@ add_library(${PROJECT_NAME} SHARED src/joint_control_model.cpp src/joint_control_panel.cpp src/mock_diagnostics_source.cpp + src/mode_model.cpp + src/motion_modes_panel.cpp src/ros_diagnostics_source.cpp src/motion_test_panel.cpp src/setup_model.cpp @@ -169,6 +174,18 @@ if(BUILD_TESTING) ) ament_target_dependencies(test_setup_model diagnostic_msgs) endif() + + ament_add_gtest(test_mode_model + test/test_mode_model.cpp + src/mode_model.cpp + TIMEOUT 60 + ) + if(TARGET test_mode_model) + target_include_directories(test_mode_model PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + ament_target_dependencies(test_mode_model diagnostic_msgs) + endif() endif() ament_export_targets(export_${PROJECT_NAME} HAS_LIBRARY_TARGET) diff --git a/waybionic_rviz_plugins/README.md b/waybionic_rviz_plugins/README.md index 41fcd0f..67e8d57 100644 --- a/waybionic_rviz_plugins/README.md +++ b/waybionic_rviz_plugins/README.md @@ -36,11 +36,11 @@ colcon test-result --verbose ## Operator panels -Both panels are in the ground station's right-hand dock, above the diagnostics panel +The panels are in the ground station's right-hand dock, above the diagnostics panel (`ground_station_rviz` stacks them; a plain `rviz2` leaves them wherever the layout puts them). -It also puts the joint control and diagnostics panels in scroll areas, so that the three together -do not make the window taller than a laptop screen; the setup panel asks for the height its text -needs and does not scroll. +It also puts the joint control and diagnostics panels in scroll areas, so that the panels together +do not make the window taller than a laptop screen; the setup and motion modes panels ask for the +height their text needs (`fitPanelHeight`) and do not scroll. **Arm setup** (`waybionic_rviz_plugins/SetupPanel`) lists the start-up steps the `setup_guide` node publishes on the latched `/arm/setup` topic (a DiagnosticArray of `setup.` rows: @@ -61,9 +61,23 @@ is off is held by the drive node, which refuses a change while the arm is enable shows that refusal and leaves the box as the topic says. A joint with no drive is shown but cannot be switched. -Both publishers repeat their message every 0.5 s, so three seconds of silence greys a panel out -as waiting. The parsing of each topic lives in a Qt-free unit (`joint_control_model.*`, -`setup_model.*`) with gtests that build fabricated messages. +**Motion modes** (`waybionic_rviz_plugins/MotionModesPanel`) has one checkbox for each mode in which +the teleop node moves the arm by itself. Chicken head mode holds the tool tip at a preset spot while +the sticks tilt and roll the tool, and demo mode moves the arm around slowly and smoothly. Each mode +has a latched topic with one row whose `state` says what it is doing (`/arm/chicken_head`: `off`, +`approach`, `hold`, `blocked` or `unavailable`; `/arm/demo`: `off`, `running`, `stopping` or +`unavailable`) and whose message says what is going on, and a `std_srvs/SetBool` service the panel +calls when the box is clicked (`/arm/chicken_head/set_enabled`, `/arm/demo/set_enabled`). As in the +joint control panel, a box follows the topic, not the click: a refusal such as "Press Start first" +is shown for a few seconds and the box stays as it was, and a row that is a warning, such as a demo +that stopped because something was in the way, is shown in the warning colour. The panel sends only +the switches, never a motion command; the teleop node moves the arm. The modes, their topics and the words for their states are one table +each in `mode_model.cpp` (`ModeSpec`), and a test in `waybionic_teleop` keeps the table in step with +the node's own module for the mode. Adding a mode to the panel is adding a table. + +All three publishers repeat their message every 0.5 s, so three seconds of silence greys a panel +out as waiting. The parsing of each topic lives in a Qt-free unit (`joint_control_model.*`, +`setup_model.*`, `mode_model.*`) with gtests that build fabricated messages. ## Package Layout @@ -71,7 +85,8 @@ as waiting. The parsing of each topic lives in a Qt-free unit (`joint_control_mo waybionic_rviz_plugins/ CMakeLists.txt # Builds the shared RViz plugin library + tests package.xml # Generic deps only; no Annin/AR4 exec deps - plugin_description.xml # Registers DiagnosticsPanel, SetupPanel, JointControlPanel, MotionTestPanel + plugin_description.xml # Registers DiagnosticsPanel, SetupPanel, MotionModesPanel, JointControlPanel, + # MotionTestPanel scripts/ temporary_diagnostics_publisher.py diagnostics_recorder.py @@ -82,6 +97,9 @@ waybionic_rviz_plugins/ joint_control_model.hpp # Qt-free parsing of /arm/joint_control joint_control_panel.hpp # Joint on/off checkboxes mock_diagnostics_source.hpp + mode_model.hpp # Qt-free parsing of the motion mode topics + motion_modes_panel.hpp # Motion mode checkboxes + panel_fit.hpp # Height a panel asks of its dock ros_diagnostics_source.hpp setup_model.hpp # Qt-free parsing of /arm/setup setup_panel.hpp # Start-up steps and the Zero button @@ -90,6 +108,8 @@ waybionic_rviz_plugins/ joint_control_model.cpp joint_control_panel.cpp mock_diagnostics_source.cpp + mode_model.cpp + motion_modes_panel.cpp ros_diagnostics_source.cpp setup_model.cpp setup_panel.cpp @@ -101,6 +121,7 @@ waybionic_rviz_plugins/ test/ test_package_metadata.py test_joint_control_model.cpp # /arm/joint_control parsing + test_mode_model.cpp # Motion mode topic parsing test_ros_diagnostics_source.cpp # Live/mock source handoff stress tests test_setup_model.cpp # /arm/setup parsing docs/ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/mode_model.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/mode_model.hpp new file mode 100644 index 0000000..177ac9b --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/mode_model.hpp @@ -0,0 +1,91 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__MODE_MODEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__MODE_MODEL_HPP_ + +#include +#include +#include +#include + +#include + +namespace waybionic_rviz_plugins +{ + +/// The teleop node republishes every mode's state every 0.5 s and on every change, so this long +/// without a message means it is gone. +constexpr std::chrono::milliseconds kTeleopQuietAfter{3000}; + +/// How a state is shown beside its checkbox. +enum class Tone +{ + Quiet, + Active, + Warning +}; + +/// One state a mode reports on its topic. +struct ModeState +{ + /// As published, for example "hold". + std::string name; + /// Shown beside the checkbox. + std::string word; + /// The mode counts as switched on, so its checkbox is ticked. + bool on{false}; + Tone tone{Tone::Quiet}; +}; + +/// A mode the teleop node switches on and off for the operator: where it reports and what it says. +struct ModeSpec +{ + /// Name of the row on the topic, for example "chicken_head". + std::string row; + /// Text of the checkbox. + std::string label; + /// What the mode does; shown while the node has nothing else to say about it. + std::string hint; + /// Latched topic with one row, and the std_srvs/SetBool service that switches the mode. + std::string topic; + std::string service; + std::vector states; +}; + +struct ModeSnapshot +{ + bool valid{false}; + /// The state reported; meaningful only when `valid`. + ModeState state; + /// What is going on, or what is wrong; may be empty while the mode is off. + std::string message; + /// The row's level was a warning: the mode cannot be used, or stopped by itself. + bool warning{false}; + /// Summary of the problem when the report is not valid; empty otherwise. + std::string error; +}; + +/// Chicken head mode: the tool tip is held at a spot while the sticks tilt and roll the tool. +const ModeSpec & chickenHeadSpec(); + +/// Demo mode: the arm moves around slowly by itself, and comes back to where it started. +const ModeSpec & demoSpec(); + +/// The modes in the order the panel lists them. +const std::vector & modeSpecs(); + +/// Reads one mode's message. Never throws: a malformed message is reported through `valid` and +/// `error` so the caller can keep showing the last good one. +ModeSnapshot parseMode(const diagnostic_msgs::msg::DiagnosticArray & array, const ModeSpec & spec); + +/// True when the teleop node should be treated as gone: nothing has been received, or the last +/// message is at least kTeleopQuietAfter old. +bool teleopQuiet( + const std::optional & last_message, + std::chrono::steady_clock::time_point now); + +/// What the panel says while a mode has no report to show. `seen_report` is whether a valid +/// report has ever arrived, and `teleop_quiet` is teleopQuiet(). +std::string modeWaitingMessage(bool seen_report, bool teleop_quiet); + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__MODE_MODEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/motion_modes_panel.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/motion_modes_panel.hpp new file mode 100644 index 0000000..1f2fe36 --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/motion_modes_panel.hpp @@ -0,0 +1,118 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__MOTION_MODES_PANEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__MOTION_MODES_PANEL_HPP_ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include + +#include + +#include "waybionic_rviz_plugins/mode_model.hpp" + +class QCheckBox; +class QLabel; +class QResizeEvent; +class QTimer; +class QWidget; + +namespace waybionic_rviz_plugins +{ + +struct ModeMailbox; + +/// Switches the teleop node's motion modes on and off: one checkbox per mode. +/// +/// In a motion mode the teleop node moves the arm by itself, for example by holding the tool tip +/// at a spot while the sticks tilt the tool, or by moving the arm around slowly. The node latches +/// each mode's state on a topic of its own and serves a SetBool service to switch it. The panel +/// only calls those services; it never publishes motion commands or any other topic. The +/// published state is the single source of truth: a checkbox changes only when the topic reports +/// a change, never because it was clicked, so a refused switch (Start not pressed, a joint +/// switched off) leaves it as it was and the node's reason is shown. +/// +/// Threading: ROS callbacks only write into a mutex-guarded mailbox, and a Qt timer drains it, so +/// all widget and bookkeeping state is touched by the Qt thread alone and no service call ever +/// blocks it. +class MotionModesPanel : public rviz_common::Panel +{ + Q_OBJECT + +public: + explicit MotionModesPanel(QWidget * parent = nullptr); + ~MotionModesPanel() override; + + void onInitialize() override; + + /// Subscribes to every mode's state and prepares the service clients on `node`. + /// onInitialize() calls this with RViz's node. Calling it again replaces the connection. + void connectToNode(rclcpp::Node::SharedPtr node); + +protected: + void resizeEvent(QResizeEvent * event) override; + +private: + using SetBool = std_srvs::srv::SetBool; + using SetBoolClient = rclcpp::Client; + + struct PendingCall + { + std::uint64_t token{0}; + std::int64_t request_id{0}; + std::chrono::steady_clock::time_point sent; + }; + + /// A mode: what it reports and says, the connection to its node, and its widgets. + struct Row + { + const ModeSpec * spec{nullptr}; + std::shared_ptr mailbox; + rclcpp::Subscription::SharedPtr subscription; + SetBoolClient::SharedPtr client; + // The last valid message, kept only while the teleop node keeps talking. + ModeSnapshot snapshot; + bool has_snapshot{false}; + std::optional last_message; + std::optional pending; + QCheckBox * checkbox{nullptr}; + QLabel * state{nullptr}; + QLabel * detail{nullptr}; + QString state_style; + QString detail_style; + }; + + void buildUi(); + void disconnectFromNode(); + + void poll(); + void applyMailbox(Row & row); + void applySnapshot(Row & row, ModeSnapshot snapshot); + void expirePendingCall(Row & row, std::chrono::steady_clock::time_point now); + void requestToggle(Row & row); + void showStatus(const QString & text); + void render(); + + rclcpp::Node::SharedPtr node_; + std::vector rows_; + std::uint64_t next_token_{0}; + + QString status_text_; + std::chrono::steady_clock::time_point status_expires_; + + QTimer * poll_timer_{nullptr}; + QLabel * connection_label_{nullptr}; + QLabel * status_label_{nullptr}; +}; + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__MOTION_MODES_PANEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/panel_fit.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/panel_fit.hpp new file mode 100644 index 0000000..5d7e43e --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/panel_fit.hpp @@ -0,0 +1,37 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__PANEL_FIT_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__PANEL_FIT_HPP_ + +#include + +#include +#include + +namespace waybionic_rviz_plugins +{ + +/// Asks for the height a panel's layout needs at the panel's current width, up to `max_height`. +/// +/// A word-wrapped label reports a one-line minimum height, and a dock gives its panel no height +/// for its width, so a long message was squeezed over the row below it. A dock or scroll area +/// that is shorter than the panel scrolls it instead. With `at_most_that`, the panel also +/// refuses more height than it needs, so a small panel leaves the rest of the dock to the panels +/// beside it. +inline void fitPanelHeight(QWidget * panel, const int max_height, const bool at_most_that = false) +{ + // Before the dock has laid the panel out it is far narrower than it will be, so the height it + // would need there is meaningless, and as a minimum it would stop the window from maximizing. + if (panel->layout() == nullptr || panel->width() < panel->minimumWidth()) { + return; + } + const int needed = std::min(panel->layout()->totalHeightForWidth(panel->width()), max_height); + if (needed > 0 && needed != panel->minimumHeight()) { + panel->setMinimumHeight(needed); + } + if (at_most_that && needed > 0 && needed != panel->maximumHeight()) { + panel->setMaximumHeight(needed); + } +} + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__PANEL_FIT_HPP_ diff --git a/waybionic_rviz_plugins/plugin_description.xml b/waybionic_rviz_plugins/plugin_description.xml index 728a130..041e4a5 100644 --- a/waybionic_rviz_plugins/plugin_description.xml +++ b/waybionic_rviz_plugins/plugin_description.xml @@ -18,6 +18,16 @@ + + + Switch the teleop node's motion modes on or off, such as chicken head mode. The teleop node + moves the arm; this panel only sends the switch and sends no motion commands. + + + docks; QList weights; for (const auto & entry : order) { diff --git a/waybionic_rviz_plugins/src/mode_model.cpp b/waybionic_rviz_plugins/src/mode_model.cpp new file mode 100644 index 0000000..cf43786 --- /dev/null +++ b/waybionic_rviz_plugins/src/mode_model.cpp @@ -0,0 +1,142 @@ +#include "waybionic_rviz_plugins/mode_model.hpp" + +#include +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +// Problem texts quote the offending message, which ends up in the panel, so keep them short +// and printable whatever the message contains. +std::string shorten(const std::string & text) +{ + constexpr std::size_t kMaxLength = 32; + std::string result = text.substr(0, kMaxLength); + for (auto & character : result) { + const auto byte = static_cast(character); + if (byte < 0x20 || byte >= 0x7f) { + character = '?'; + } + } + if (text.size() > kMaxLength) { + result += "..."; + } + return result; +} + +} // namespace + +// The states, row, topic and service in each table here are the ones waybionic_teleop's module for +// the mode publishes (chicken_head, demo_mode); a test in waybionic_teleop keeps the two in step. +const ModeSpec & chickenHeadSpec() +{ + static const ModeSpec spec{ + "chicken_head", "Chicken head mode", + "Moves the tool tip to a preset spot and holds it there while the sticks tilt and roll the " + "tool.", + "/arm/chicken_head", "/arm/chicken_head/set_enabled", + { + {"off", "off", false, Tone::Quiet}, + {"approach", "moving to the head spot", true, Tone::Active}, + {"hold", "holding", true, Tone::Active}, + {"blocked", "blocked", true, Tone::Warning}, + {"unavailable", "unavailable", false, Tone::Quiet}, + }}; + return spec; +} + +const ModeSpec & demoSpec() +{ + static const ModeSpec spec{ + "demo", "Demo mode", + "The arm moves around by itself, slowly and smoothly, and comes back to where it started when " + "you switch it off. Press Start first.", + "/arm/demo", "/arm/demo/set_enabled", + { + {"off", "off", false, Tone::Quiet}, + {"running", "running", true, Tone::Active}, + {"stopping", "returning", false, Tone::Active}, + {"unavailable", "unavailable", false, Tone::Quiet}, + }}; + return spec; +} + +const std::vector & modeSpecs() +{ + static const std::vector specs{&chickenHeadSpec(), &demoSpec()}; + return specs; +} + +ModeSnapshot parseMode(const diagnostic_msgs::msg::DiagnosticArray & array, const ModeSpec & spec) +{ + ModeSnapshot snapshot; + const diagnostic_msgs::msg::DiagnosticStatus * row = nullptr; + for (const auto & status : array.status) { + if (status.name != spec.row) { + continue; + } + if (row != nullptr) { + snapshot.error = "duplicate " + spec.row + " status"; + return snapshot; + } + row = &status; + } + if (row == nullptr) { + snapshot.error = "no " + spec.row + " status"; + return snapshot; + } + + const std::string * state_text = nullptr; + for (const auto & item : row->values) { + if (item.key != "state") { + continue; + } + if (state_text != nullptr) { + snapshot.error = "duplicate 'state' value"; + return snapshot; + } + state_text = &item.value; + } + if (state_text == nullptr) { + snapshot.error = "missing 'state' value"; + return snapshot; + } + const auto known = std::find_if( + spec.states.begin(), spec.states.end(), + [state_text](const ModeState & state) {return state.name == *state_text;}); + if (known == spec.states.end()) { + snapshot.error = "unknown state '" + shorten(*state_text) + "'"; + return snapshot; + } + + snapshot.state = *known; + snapshot.message = row->message; + snapshot.warning = row->level >= diagnostic_msgs::msg::DiagnosticStatus::WARN; + snapshot.valid = true; + return snapshot; +} + +bool teleopQuiet( + const std::optional & last_message, + const std::chrono::steady_clock::time_point now) +{ + return !last_message.has_value() || now - *last_message >= kTeleopQuietAfter; +} + +std::string modeWaitingMessage(const bool seen_report, const bool teleop_quiet) +{ + if (!teleop_quiet) { + return "Waiting for a valid report..."; + } + if (seen_report) { + return "The teleop node (xbox_teleop) has stopped reporting."; + } + return "Waiting for the teleop node (xbox_teleop). It runs when the station is started for " + "the arm (teleop:=true)."; +} + +} // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/src/motion_modes_panel.cpp b/waybionic_rviz_plugins/src/motion_modes_panel.cpp new file mode 100644 index 0000000..59ebaa8 --- /dev/null +++ b/waybionic_rviz_plugins/src/motion_modes_panel.cpp @@ -0,0 +1,374 @@ +#include "waybionic_rviz_plugins/motion_modes_panel.hpp" + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "waybionic_rviz_plugins/panel_fit.hpp" + +namespace waybionic_rviz_plugins +{ +namespace +{ + +constexpr int kPollIntervalMs = 100; +// The most height the panel asks of its dock for its text; a dock that is shorter scrolls it. +constexpr int kMaxFittedHeight = 360; +constexpr std::chrono::seconds kServiceTimeout{5}; +constexpr std::chrono::seconds kStatusLifetime{8}; + +constexpr const char * kPanelStyle = R"( +QWidget { + background-color: #071019; + color: #e8f1f8; + font-family: "Segoe UI", "Ubuntu", sans-serif; + font-size: 12px; +} +QLabel#PanelTitle { + font-size: 15px; + font-weight: 700; +} +QLabel#Muted { + color: #8ea3b1; +} +QLabel#Warning { + color: #ffb84d; + font-weight: 700; +} +QCheckBox { + font-weight: 700; + spacing: 8px; +} +QCheckBox:disabled { + color: #5d7282; +} +)"; + +constexpr const char * kActiveStyle = "color: #3ddc84; font-weight: 700;"; +constexpr const char * kWarningStyle = "color: #ffb84d; font-weight: 700;"; +constexpr const char * kQuietStyle = "color: #8ea3b1;"; +constexpr const char * kWaitingStyle = "color: #5d7282;"; + +const char * styleFor(const Tone tone) +{ + switch (tone) { + case Tone::Active: + return kActiveStyle; + case Tone::Warning: + return kWarningStyle; + case Tone::Quiet: + return kQuietStyle; + } + return kWaitingStyle; +} + +} // namespace + +/// What the ROS threads hand to the Qt thread, for one mode. Callbacks only ever write here. +struct ModeMailbox +{ + struct Reply + { + std::uint64_t token{0}; + bool success{false}; + std::string message; + }; + + std::mutex mutex; + std::optional snapshot; + std::optional received_at; + std::deque replies; +}; + +MotionModesPanel::MotionModesPanel(QWidget * parent) +: rviz_common::Panel(parent) +{ + buildUi(); + poll_timer_ = new QTimer(this); + connect(poll_timer_, &QTimer::timeout, this, [this]() {poll();}); + poll_timer_->start(kPollIntervalMs); + render(); +} + +MotionModesPanel::~MotionModesPanel() +{ + if (poll_timer_ != nullptr) { + poll_timer_->stop(); + } + disconnectFromNode(); +} + +void MotionModesPanel::onInitialize() +{ + if (auto ros_node_abstraction = getDisplayContext()->getRosNodeAbstraction().lock()) { + connectToNode(ros_node_abstraction->get_raw_node()); + } +} + +void MotionModesPanel::connectToNode(rclcpp::Node::SharedPtr node) +{ + disconnectFromNode(); + node_ = std::move(node); + if (!node_) { + return; + } + for (auto & row : rows_) { + { + std::lock_guard lock(row.mailbox->mutex); + row.mailbox->snapshot.reset(); + row.mailbox->received_at.reset(); + row.mailbox->replies.clear(); + } + row.subscription = node_->create_subscription( + row.spec->topic, rclcpp::QoS(1).reliable().transient_local(), + [mailbox = row.mailbox, spec = row.spec]( + diagnostic_msgs::msg::DiagnosticArray::ConstSharedPtr message) { + auto snapshot = parseMode(*message, *spec); + std::lock_guard lock(mailbox->mutex); + mailbox->snapshot = std::move(snapshot); + mailbox->received_at = std::chrono::steady_clock::now(); + }); + row.client = node_->create_client(row.spec->service); + } +} + +void MotionModesPanel::disconnectFromNode() +{ + for (auto & row : rows_) { + row.subscription.reset(); + if (row.pending.has_value() && row.client) { + row.client->remove_pending_request(row.pending->request_id); + } + row.pending.reset(); + row.client.reset(); + row.has_snapshot = false; + row.snapshot = ModeSnapshot{}; + row.last_message.reset(); + } + node_.reset(); +} + +void MotionModesPanel::buildUi() +{ + setStyleSheet(kPanelStyle); + setMinimumWidth(320); + + auto * root_layout = new QVBoxLayout(this); + root_layout->setContentsMargins(10, 10, 10, 10); + root_layout->setSpacing(6); + + auto * title = new QLabel("Motion modes"); + title->setObjectName("PanelTitle"); + root_layout->addWidget(title); + + connection_label_ = new QLabel(); + connection_label_->setObjectName("Muted"); + connection_label_->setWordWrap(true); + root_layout->addWidget(connection_label_); + + for (const ModeSpec * spec : modeSpecs()) { + Row row; + row.spec = spec; + row.mailbox = std::make_shared(); + row.checkbox = new QCheckBox(QString::fromStdString(spec->label)); + row.state = new QLabel(); + row.detail = new QLabel(); + row.detail->setObjectName("Muted"); + row.detail->setWordWrap(true); + + auto * switch_row = new QHBoxLayout(); + switch_row->addWidget(row.checkbox); + switch_row->addStretch(1); + switch_row->addWidget(row.state); + root_layout->addLayout(switch_row); + root_layout->addWidget(row.detail); + + // The checkbox follows the published state, not the click: the click only asks. + const auto index = rows_.size(); + connect(row.checkbox, &QCheckBox::clicked, this, [this, index](bool) { + requestToggle(rows_[index]); + render(); + }); + rows_.push_back(std::move(row)); + } + + status_label_ = new QLabel(); + status_label_->setObjectName("Warning"); + status_label_->setWordWrap(true); + root_layout->addWidget(status_label_); + root_layout->addStretch(1); +} + +void MotionModesPanel::resizeEvent(QResizeEvent * event) +{ + rviz_common::Panel::resizeEvent(event); + fitPanelHeight(this, kMaxFittedHeight, true); +} + +void MotionModesPanel::poll() +{ + const auto now = std::chrono::steady_clock::now(); + for (auto & row : rows_) { + applyMailbox(row); + expirePendingCall(row, now); + } + render(); +} + +void MotionModesPanel::applyMailbox(Row & row) +{ + std::optional snapshot; + std::optional received_at; + std::deque replies; + { + std::lock_guard lock(row.mailbox->mutex); + snapshot.swap(row.mailbox->snapshot); + received_at = row.mailbox->received_at; + replies.swap(row.mailbox->replies); + } + if (received_at.has_value()) { + row.last_message = received_at; + } + if (snapshot.has_value()) { + applySnapshot(row, std::move(*snapshot)); + } + for (const auto & reply : replies) { + if (!row.pending.has_value() || row.pending->token != reply.token) { + continue; // Answers a call that already timed out. + } + row.pending.reset(); + if (!reply.success) { + showStatus(QString::fromStdString(reply.message)); + } + } +} + +void MotionModesPanel::applySnapshot(Row & row, ModeSnapshot snapshot) +{ + if (!snapshot.valid) { + // Keep showing the last good report, and say that this one was ignored. + showStatus( + QString::fromStdString( + "Ignoring a malformed " + row.spec->row + " report: " + snapshot.error)); + return; + } + row.snapshot = std::move(snapshot); + row.has_snapshot = true; +} + +void MotionModesPanel::expirePendingCall(Row & row, const std::chrono::steady_clock::time_point now) +{ + if (!row.pending.has_value() || now - row.pending->sent <= kServiceTimeout) { + return; + } + row.client->remove_pending_request(row.pending->request_id); + row.pending.reset(); + showStatus("No answer from the teleop node"); +} + +void MotionModesPanel::requestToggle(Row & row) +{ + if (!node_ || !row.client || !row.has_snapshot || row.pending.has_value() || + teleopQuiet(row.last_message, std::chrono::steady_clock::now())) + { + return; + } + if (!row.client->service_is_ready()) { + showStatus("The teleop node is not available"); + return; + } + auto request = std::make_shared(); + request->data = !row.snapshot.state.on; + PendingCall call; + call.token = ++next_token_; + call.sent = std::chrono::steady_clock::now(); + const auto sent = row.client->async_send_request( + request, + [mailbox = row.mailbox, token = call.token](SetBoolClient::SharedFuture future) { + const auto response = future.get(); + std::lock_guard lock(mailbox->mutex); + mailbox->replies.push_back({token, response->success, response->message}); + }); + call.request_id = sent.request_id; + row.pending = call; +} + +void MotionModesPanel::showStatus(const QString & text) +{ + status_text_ = text; + status_expires_ = std::chrono::steady_clock::now() + kStatusLifetime; +} + +void MotionModesPanel::render() +{ + const auto now = std::chrono::steady_clock::now(); + QString waiting_for; + + for (auto & row : rows_) { + const bool quiet = teleopQuiet(row.last_message, now); + const bool shown = row.has_snapshot && !quiet; + const bool pending = row.pending.has_value(); + if (!shown && waiting_for.isEmpty()) { + waiting_for = QString::fromStdString(modeWaitingMessage(row.has_snapshot, quiet)); + } + + QString word = QString::fromUtf8("\xE2\x80\x94"); + QString style = kWaitingStyle; + QString detail = QString::fromStdString(row.spec->hint); + QString detail_style; + bool on = false; + if (shown) { + on = row.snapshot.state.on; + word = QString::fromStdString(row.snapshot.state.word); + style = QString::fromUtf8(styleFor(row.snapshot.state.tone)); + if (!row.snapshot.message.empty()) { + detail = QString::fromStdString(row.snapshot.message); + if (row.snapshot.warning) { + detail_style = kWarningStyle; + } + } + if (pending) { + word = on ? "switching off..." : "switching on..."; + } + } + + { + const QSignalBlocker blocker(row.checkbox); + row.checkbox->setChecked(on); + row.checkbox->setEnabled(shown && !pending); + } + row.state->setText(word); + if (row.state_style != style) { + row.state->setStyleSheet(style); + row.state_style = style; + } + row.detail->setText(detail); + if (row.detail_style != detail_style) { + row.detail->setStyleSheet(detail_style); + row.detail_style = detail_style; + } + row.checkbox->setToolTip(detail); + } + + connection_label_->setText(waiting_for); + connection_label_->setVisible(!waiting_for.isEmpty()); + status_label_->setText(now < status_expires_ ? status_text_ : QString()); + fitPanelHeight(this, kMaxFittedHeight, true); +} + +} // namespace waybionic_rviz_plugins + +PLUGINLIB_EXPORT_CLASS(waybionic_rviz_plugins::MotionModesPanel, rviz_common::Panel) diff --git a/waybionic_rviz_plugins/src/setup_panel.cpp b/waybionic_rviz_plugins/src/setup_panel.cpp index 1d48c21..235ab63 100644 --- a/waybionic_rviz_plugins/src/setup_panel.cpp +++ b/waybionic_rviz_plugins/src/setup_panel.cpp @@ -20,6 +20,8 @@ #include #include +#include "waybionic_rviz_plugins/panel_fit.hpp" + namespace waybionic_rviz_plugins { namespace @@ -392,21 +394,9 @@ void SetupPanel::resizeEvent(QResizeEvent * event) fitHeight(); } -// A word-wrapped label reports a one-line minimum height, and a dock gives its panel no height -// for its width, so a long message was squeezed over the row below it. Asking for the height the -// layout needs at this width keeps the text readable: a dock or scroll area that is shorter -// scrolls the panel instead. void SetupPanel::fitHeight() { - // Before the dock has laid the panel out it is far narrower than it will be, so the height it - // would need there is meaningless, and as a minimum it would stop the window from maximizing. - if (layout() == nullptr || width() < minimumWidth()) { - return; - } - const int needed = std::min(layout()->totalHeightForWidth(width()), kMaxFittedHeight); - if (needed > 0 && needed != minimumHeight()) { - setMinimumHeight(needed); - } + fitPanelHeight(this, kMaxFittedHeight); } void SetupPanel::render() diff --git a/waybionic_rviz_plugins/test/test_mode_model.cpp b/waybionic_rviz_plugins/test/test_mode_model.cpp new file mode 100644 index 0000000..6d8a574 --- /dev/null +++ b/waybionic_rviz_plugins/test/test_mode_model.cpp @@ -0,0 +1,367 @@ +// Tests for the Qt-free parsing of the mode topics. They build fabricated DiagnosticArray +// messages, so no teleop node or ROS graph is needed. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "waybionic_rviz_plugins/mode_model.hpp" + +namespace waybionic_rviz_plugins +{ +namespace +{ + +using diagnostic_msgs::msg::DiagnosticArray; +using diagnostic_msgs::msg::DiagnosticStatus; +using diagnostic_msgs::msg::KeyValue; +using namespace std::chrono_literals; + +KeyValue keyValue(const std::string & key, const std::string & value) +{ + KeyValue item; + item.key = key; + item.value = value; + return item; +} + +DiagnosticStatus makeStatus( + const std::string & row, const std::string & state, const std::string & message = "", + const unsigned char level = DiagnosticStatus::OK) +{ + DiagnosticStatus status; + status.name = row; + status.message = message; + status.level = level; + status.values.push_back(keyValue("state", state)); + return status; +} + +DiagnosticArray makeArray(const std::vector & statuses) +{ + DiagnosticArray array; + array.status = statuses; + return array; +} + +// The first state of the mode that is on, and its first state that is off. +const ModeState & anOnState(const ModeSpec & spec) +{ + for (const auto & state : spec.states) { + if (state.on) { + return state; + } + } + ADD_FAILURE() << spec.row << " has no state that is on"; + return spec.states.front(); +} + +TEST(ModeModel, ListsChickenHeadThenDemo) +{ + const auto & specs = modeSpecs(); + ASSERT_EQ(specs.size(), 2u); + EXPECT_EQ(specs[0], &chickenHeadSpec()); + EXPECT_EQ(specs[1], &demoSpec()); +} + +TEST(ModeModel, EveryModeHasItsOwnRowTopicAndService) +{ + std::vector names; + for (const auto * spec : modeSpecs()) { + for (const auto & name : {spec->row, spec->topic, spec->service}) { + EXPECT_FALSE(name.empty()); + for (const auto & other : names) { + EXPECT_NE(name, other) << "shared by two modes"; + } + } + names.push_back(spec->row); + names.push_back(spec->topic); + names.push_back(spec->service); + } +} + +TEST(ModeModel, EveryModeCanBeOffAndSaysSoWithoutBeingOn) +{ + for (const auto * spec : modeSpecs()) { + bool found = false; + for (const auto & state : spec->states) { + if (state.name == "off") { + found = true; + EXPECT_FALSE(state.on) << spec->row; + } + } + EXPECT_TRUE(found) << spec->row << " has no off state"; + } +} + +TEST(ModeModel, NoModeHasTwoStatesOfOneName) +{ + for (const auto * spec : modeSpecs()) { + for (std::size_t first = 0; first < spec->states.size(); ++first) { + for (std::size_t second = first + 1; second < spec->states.size(); ++second) { + EXPECT_NE(spec->states[first].name, spec->states[second].name) << spec->row; + } + } + } +} + +TEST(ModeModel, ParsesEveryStateOfEveryMode) +{ + for (const auto * spec : modeSpecs()) { + for (const auto & expected : spec->states) { + const auto snapshot = parseMode(makeArray({makeStatus(spec->row, expected.name)}), *spec); + ASSERT_TRUE(snapshot.valid) << spec->row << " " << expected.name << ": " << snapshot.error; + EXPECT_EQ(snapshot.state.name, expected.name); + EXPECT_EQ(snapshot.state.on, expected.on); + EXPECT_TRUE(snapshot.error.empty()); + } + } +} + +TEST(ModeModel, KeepsTheMessageForTheOperator) +{ + const auto & spec = chickenHeadSpec(); + const auto snapshot = parseMode( + makeArray({makeStatus(spec.row, "blocked", "The way to the head position is blocked")}), spec); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(snapshot.message, "The way to the head position is blocked"); +} + +TEST(ModeModel, AnOffReportNeedsNoMessage) +{ + for (const auto * spec : modeSpecs()) { + const auto snapshot = parseMode(makeArray({makeStatus(spec->row, "off")}), *spec); + + ASSERT_TRUE(snapshot.valid) << spec->row; + EXPECT_TRUE(snapshot.message.empty()); + EXPECT_FALSE(snapshot.warning); + } +} + +TEST(ModeModel, ReportsWhetherTheRowIsAWarning) +{ + const auto & spec = chickenHeadSpec(); + const auto calm = parseMode(makeArray({makeStatus(spec.row, "hold", "x")}), spec); + const auto warn = parseMode( + makeArray({makeStatus(spec.row, "off", "stopped", DiagnosticStatus::WARN)}), spec); + const auto error = parseMode( + makeArray({makeStatus(spec.row, "off", "failed", DiagnosticStatus::ERROR)}), spec); + + EXPECT_FALSE(calm.warning); + EXPECT_TRUE(warn.warning); + EXPECT_TRUE(error.warning); +} + +TEST(ModeModel, IgnoresRowsWithOtherNames) +{ + const auto & spec = chickenHeadSpec(); + const auto snapshot = parseMode( + makeArray({makeStatus("teleop", "off", "other"), makeStatus("demo", "running"), + makeStatus(spec.row, "hold", "Holding the tip")}), spec); + + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_EQ(snapshot.state.name, "hold"); + EXPECT_EQ(snapshot.message, "Holding the tip"); +} + +TEST(ModeModel, RejectsAnEmptyArray) +{ + const auto & spec = chickenHeadSpec(); + const auto snapshot = parseMode(DiagnosticArray(), spec); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.error, "no chicken_head status"); +} + +TEST(ModeModel, RejectsAnArrayWithoutTheRow) +{ + const auto & spec = chickenHeadSpec(); + const auto snapshot = parseMode(makeArray({makeStatus("joint_1", "hold")}), spec); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.error, "no chicken_head status"); +} + +TEST(ModeModel, RejectsDuplicateRows) +{ + const auto & spec = chickenHeadSpec(); + const auto snapshot = parseMode( + makeArray({makeStatus(spec.row, "off"), makeStatus(spec.row, "hold")}), spec); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.error, "duplicate chicken_head status"); +} + +TEST(ModeModel, RejectsAMissingState) +{ + const auto & spec = chickenHeadSpec(); + auto status = makeStatus(spec.row, "hold"); + status.values.clear(); + + const auto snapshot = parseMode(makeArray({status}), spec); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.error, "missing 'state' value"); +} + +TEST(ModeModel, RejectsADuplicateState) +{ + const auto & spec = chickenHeadSpec(); + auto status = makeStatus(spec.row, "hold"); + status.values.push_back(keyValue("state", "off")); + + const auto snapshot = parseMode(makeArray({status}), spec); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.error, "duplicate 'state' value"); +} + +TEST(ModeModel, RejectsAStateTheModeDoesNotHave) +{ + const auto & spec = chickenHeadSpec(); + const auto snapshot = parseMode(makeArray({makeStatus(spec.row, "dancing")}), spec); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.error, "unknown state 'dancing'"); +} + +TEST(ModeModel, ShortensAndCleansAnUnknownStateInTheError) +{ + const auto & spec = chickenHeadSpec(); + const auto snapshot = parseMode( + makeArray({makeStatus(spec.row, std::string("bad\nstate") + std::string(60, 'x'))}), spec); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.error.find('\n'), std::string::npos); + EXPECT_LT(snapshot.error.size(), 80u); + EXPECT_NE(snapshot.error.find("..."), std::string::npos); +} + +TEST(ModeModel, ChickenHeadStatesAreOnWhileItMovesHoldsOrIsBlocked) +{ + const auto & spec = chickenHeadSpec(); + const auto on = [&spec](const std::string & name) { + return parseMode(makeArray({makeStatus(spec.row, name)}), spec).state.on; + }; + + EXPECT_FALSE(on("off")); + EXPECT_TRUE(on("approach")); + EXPECT_TRUE(on("hold")); + EXPECT_TRUE(on("blocked")); + EXPECT_FALSE(on("unavailable")); +} + +TEST(ModeModel, ChickenHeadStatesAreNamedInAWord) +{ + const auto & spec = chickenHeadSpec(); + const auto word = [&spec](const std::string & name) { + return parseMode(makeArray({makeStatus(spec.row, name)}), spec).state.word; + }; + + EXPECT_EQ(word("off"), "off"); + EXPECT_EQ(word("approach"), "moving to the head spot"); + EXPECT_EQ(word("hold"), "holding"); + EXPECT_EQ(word("blocked"), "blocked"); + EXPECT_EQ(word("unavailable"), "unavailable"); +} + +TEST(ModeModel, ABlockedModeIsShownAsAWarningAndAHoldingOneAsActive) +{ + const auto & spec = chickenHeadSpec(); + const auto tone = [&spec](const std::string & name) { + return parseMode(makeArray({makeStatus(spec.row, name)}), spec).state.tone; + }; + + EXPECT_EQ(tone("blocked"), Tone::Warning); + EXPECT_EQ(tone("hold"), Tone::Active); + EXPECT_EQ(tone("off"), Tone::Quiet); +} + +TEST(ModeModel, DemoIsOnWhileItRunsAndNotWhileItReturns) +{ + const auto & spec = demoSpec(); + const auto parse = [&spec](const std::string & name) { + return parseMode(makeArray({makeStatus(spec.row, name)}), spec).state; + }; + + EXPECT_FALSE(parse("off").on); + EXPECT_TRUE(parse("running").on); + EXPECT_FALSE(parse("stopping").on); + EXPECT_FALSE(parse("unavailable").on); + EXPECT_EQ(parse("running").word, "running"); + EXPECT_EQ(parse("stopping").word, "returning"); + // Returning is something going on, so it is not shown as quiet, but it is not a problem. + EXPECT_EQ(parse("stopping").tone, Tone::Active); + EXPECT_EQ(parse("off").tone, Tone::Quiet); +} + +TEST(ModeModel, ADemoThatStoppedItselfIsAnOffStateWithAWarning) +{ + const auto & spec = demoSpec(); + const auto snapshot = parseMode( + makeArray({makeStatus( + spec.row, "off", "Demo stopped: blocked by forearm_link: table", + DiagnosticStatus::WARN)}), spec); + + ASSERT_TRUE(snapshot.valid); + EXPECT_FALSE(snapshot.state.on); + EXPECT_TRUE(snapshot.warning); + EXPECT_EQ(snapshot.message, "Demo stopped: blocked by forearm_link: table"); +} + +TEST(ModeModel, EachModeOnlyReadsItsOwnRowAndStates) +{ + const auto array = makeArray({makeStatus("chicken_head", "hold"), makeStatus("demo", "running")}); + + const auto head = parseMode(array, chickenHeadSpec()); + const auto demo = parseMode(array, demoSpec()); + ASSERT_TRUE(head.valid); + ASSERT_TRUE(demo.valid); + EXPECT_EQ(head.state.name, "hold"); + EXPECT_EQ(demo.state.name, "running"); + + // A state of one mode is not a state of the other. + const auto wrong = parseMode(makeArray({makeStatus("demo", "hold")}), demoSpec()); + EXPECT_FALSE(wrong.valid); + EXPECT_EQ(wrong.error, "unknown state 'hold'"); + EXPECT_EQ(parseMode(makeArray({makeStatus("demo", "running")}), chickenHeadSpec()).error, + "no chicken_head status"); +} + +TEST(ModeModel, AnOnStateExistsForEveryMode) +{ + for (const auto * spec : modeSpecs()) { + EXPECT_TRUE(anOnState(*spec).on); + } +} + +TEST(ModeModel, TheTeleopNodeIsQuietUntilItHasReported) +{ + const auto now = std::chrono::steady_clock::now(); + + EXPECT_TRUE(teleopQuiet(std::nullopt, now)); + EXPECT_FALSE(teleopQuiet(now - 100ms, now)); + EXPECT_FALSE(teleopQuiet(now - (kTeleopQuietAfter - 1ms), now)); + EXPECT_TRUE(teleopQuiet(now - kTeleopQuietAfter, now)); + EXPECT_TRUE(teleopQuiet(now - 1h, now)); +} + +TEST(ModeModel, TheWaitingMessageSaysWhatIsMissing) +{ + EXPECT_EQ(modeWaitingMessage(false, false), "Waiting for a valid report..."); + EXPECT_EQ(modeWaitingMessage(true, false), "Waiting for a valid report..."); + EXPECT_NE(modeWaitingMessage(false, true).find("teleop:=true"), std::string::npos); + EXPECT_NE(modeWaitingMessage(true, true).find("stopped reporting"), std::string::npos); +} + +} // namespace +} // namespace waybionic_rviz_plugins diff --git a/waybionic_teleop/config/xbox_teleop.yaml b/waybionic_teleop/config/xbox_teleop.yaml index 10c18b3..f4e8eb2 100644 --- a/waybionic_teleop/config/xbox_teleop.yaml +++ b/waybionic_teleop/config/xbox_teleop.yaml @@ -51,6 +51,35 @@ xbox_teleop: joints: [joint_1, joint_2, joint_3, joint_4, joint_5] axes: [left_y, right_y, right_x] scales: [1.0, 1.0, 1.0] + # Chicken head mode (the Chicken head panel in RViz): the tool tip goes to this spot in + # base_link, 30 cm forward and 55 cm up with the tool pointing forward (90 degrees from straight + # up), and stays there while the other joints move. The first stick tilts the tool about the + # tip (up tilts it up) and the second rolls it. The tool can tilt through about 215 degrees at + # this spot. + chicken_head: + position: [0.30, 0.0, 0.55] + pitch_deg: 90.0 + axes: [left_y, right_x] + scales: [1.0, 1.0] + # Demo mode (the Motion modes panel in RViz): the arm moves around by itself, slowly and + # smoothly, and the sticks do nothing. Each joint swings about the pose the arm is in when the + # mode starts: it makes `cycles` whole swings of up to `amplitudes_deg` in every `loop_s` + # seconds, starting `phases_deg` into its swing, so the arm does not repeat itself before + # the loop is over. The swing grows over `ramp_s` seconds at the start and shrinks over as + # long when the mode is switched off, which brings the arm back to where it started. A joint + # stays `margin_deg` clear of its limits, and one with less room than `min_swing_deg` stays + # still. No joint may go faster than `max_speed_deg_s`: settings that would are refused when + # teleop starts. The speed level can slow the demo but never speeds it up. + demo: + joints: [joint_1, joint_2, joint_3, joint_4, joint_5] + amplitudes_deg: [30.0, 15.0, 25.0, 20.0, 35.0] + cycles: [3, 5, 4, 6, 2] + phases_deg: [0.0, 140.0, 250.0, 70.0, 200.0] + loop_s: 120.0 + ramp_s: 12.0 + margin_deg: 10.0 + min_swing_deg: 3.0 + max_speed_deg_s: 12.0 max_linear_speed_mm_s: 50.0 max_linear_accel_mm_s2: 250.0 max_tilt_speed_deg_s: 30.0 diff --git a/waybionic_teleop/test/conftest.py b/waybionic_teleop/test/conftest.py index 01c0267..eea702d 100644 --- a/waybionic_teleop/test/conftest.py +++ b/waybionic_teleop/test/conftest.py @@ -73,7 +73,7 @@ def flatten(values, prefix=''): return flat -@pytest.fixture +@pytest.fixture(scope='session') def parameters(): def load(file_name, node_name): with open(CONFIG / file_name, encoding='utf-8') as stream: diff --git a/waybionic_teleop/test/test_carrier_relay.py b/waybionic_teleop/test/test_carrier_relay.py index d812def..cf5b77f 100644 --- a/waybionic_teleop/test/test_carrier_relay.py +++ b/waybionic_teleop/test/test_carrier_relay.py @@ -203,8 +203,12 @@ def test_the_relay_starts_listening_once_the_carrier_is_plugged_in(): assert time.monotonic() < deadline, 'the relay never listened' time.sleep(0.05) client.settimeout(2.0) - client.sendall(b't00121234\r') - assert client.recv(64) == b't00121234\r' + frame = b't00121234\r' + client.sendall(frame) + echoed = b'' + while len(echoed) < len(frame): + echoed += client.recv(64) + assert echoed == frame client.close() assert 'Carrier on COM5' in messages finally: diff --git a/waybionic_teleop/test/test_chicken_head.py b/waybionic_teleop/test/test_chicken_head.py new file mode 100644 index 0000000..3ac861d --- /dev/null +++ b/waybionic_teleop/test/test_chicken_head.py @@ -0,0 +1,334 @@ +"""Chicken head mode: the tip goes to a head spot and stays there while the tool tilts.""" + +import math +from pathlib import Path + +import pytest + +from waybionic_teleop.collision import ArmCollision +from waybionic_teleop.gamepad import AXES, BUTTONS +from waybionic_teleop.kinematics import ArmKinematics +from waybionic_teleop.teleop import ArmTeleop, axis_words, config_from_parameters + +LIMITS = {'joint_1': (-math.pi, math.pi), 'joint_2': (-1.5708, 1.5708), + 'joint_3': (-1.5708, 1.5708), 'joint_4': (-1.5708, 1.5708), + 'joint_5': (-1.5708, 1.5708)} +HOME = dict.fromkeys([*LIMITS, 'tool_grip'], 0.0) +URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' + / 'waybionic_arm.urdf').read_text(encoding='utf-8') +DT = 1.0 / 120.0 +TIP_TOLERANCE = 0.0005 + + +def sample(*pressed, **axes): + return [axes.get(name, 0.0) for name in AXES], [int(name in pressed) for name in BUTTONS] + + +def run(teleop, seconds, *pressed, **axes): + for _ in range(round(seconds / DT)): + teleop.update(*sample(*pressed, **axes), dict(teleop.targets), DT) + + +def press(teleop, button): + teleop.update(*sample(button), dict(teleop.targets), DT) + teleop.update(*sample(), dict(teleop.targets), DT) + + +@pytest.fixture +def arm(): + return ArmKinematics.from_urdf(URDF) + + +@pytest.fixture +def params(parameters): + return parameters('xbox_teleop.yaml', 'xbox_teleop') + + +def build(params, arm, **options): + options.setdefault('collision', ArmCollision.from_urdf(URDF, 0.0, 0.01)) + return ArmTeleop(config_from_parameters(params), LIMITS, arm, **options) + + +def enabled(teleop): + teleop.update(*sample('start'), HOME, DT) + teleop.update(*sample(), HOME, DT) + assert teleop.enabled + return teleop + + +@pytest.fixture +def teleop(params, arm): + return enabled(build(params, arm)) + + +def reach_head(teleop, seconds=40.0): + ok, message = teleop.set_head_mode(True) + assert ok, message + for _ in range(round(seconds / DT)): + teleop.update(*sample(), dict(teleop.targets), DT) + if teleop.head_status()[0] == 'hold': + # The sticks are centred as it arrives, as an operator's hands are. + teleop.update(*sample(), dict(teleop.targets), DT) + return + pytest.fail(f'never reached the head position: {teleop.head_status()}') + + +def tip(arm, teleop): + return arm.forward(teleop.targets) + + +def test_the_head_spot_and_sticks_come_from_the_config(teleop): + head = teleop.config.head + assert head.position == (0.30, 0.0, 0.55) + assert math.isclose(head.pitch, math.pi / 2) + assert (head.tilt_axis, head.roll_axis) == ('left_y', 'right_x') + + +@pytest.mark.parametrize('axis, words', [ + ('left_y', 'left stick'), ('right_x', 'right stick'), ('left_trigger', 'left trigger')]) +def test_axes_are_named_the_way_an_operator_says_them(axis, words): + assert axis_words(axis) == words + + +def test_the_hold_message_names_the_configured_inputs(params, arm): + teleop = enabled(build({**params, 'chicken_head.axes': ['right_y', 'left_x']}, arm)) + reach_head(teleop) + assert 'the right stick tilts the tool, the left stick rolls it' in teleop.head_status()[1] + + +def test_the_mode_is_off_until_it_is_switched_on(teleop): + assert teleop.head_status()[0] == 'off' + assert teleop.head is None + + +def test_the_tip_goes_to_the_head_spot_and_holds_there(teleop, arm): + reach_head(teleop) + position, pitch = tip(arm, teleop) + assert math.dist(position, teleop.config.head.position) < TIP_TOLERANCE + assert math.isclose(pitch, teleop.config.head.pitch, abs_tol=math.radians(0.5)) + assert 'left stick' in teleop.head_status()[1] and 'right stick' in teleop.head_status()[1] + + +def test_the_approach_never_moves_a_joint_faster_than_the_speed_limit(teleop): + ok, message = teleop.set_head_mode(True) + assert ok, message + previous, fastest = dict(teleop.targets), 0.0 + for _ in range(round(40.0 / DT)): + teleop.update(*sample(), dict(teleop.targets), DT) + fastest = max(fastest, *(abs(teleop.targets[joint] - previous[joint]) / DT + for joint in LIMITS)) + for joint, (lower, upper) in LIMITS.items(): + assert lower <= teleop.targets[joint] <= upper + previous = dict(teleop.targets) + if teleop.head_status()[0] == 'hold': + break + assert teleop.head_status()[0] == 'hold' + assert 0.0 < fastest <= teleop.config.max_speed * 1.0001 + + +def test_the_approach_ignores_the_sticks(teleop, arm): + ok, _ = teleop.set_head_mode(True) + assert ok + for _ in range(round(40.0 / DT)): + teleop.update(*sample(left_y=1.0, right_x=1.0), dict(teleop.targets), DT) + if teleop.head_status()[0] == 'hold': + break + assert math.dist(tip(arm, teleop)[0], teleop.config.head.position) < TIP_TOLERANCE + + +def test_a_stick_still_held_on_arrival_waits_for_the_centre(teleop, arm): + ok, _ = teleop.set_head_mode(True) + assert ok + for _ in range(round(40.0 / DT)): + teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) + if teleop.head_status()[0] == 'hold': + break + arrived = dict(teleop.targets) + run(teleop, 1.0, left_y=1.0) + assert teleop.targets == arrived + assert 'Center' in teleop.note + run(teleop, 0.1) + run(teleop, 1.0, left_y=1.0) + assert teleop.targets != arrived + + +def test_the_left_stick_tilts_the_tool_while_the_tip_stays(teleop, arm): + reach_head(teleop) + head, level = teleop.config.head.position, tip(arm, teleop)[1] + run(teleop, 3.0, left_y=1.0) + position, pitch = tip(arm, teleop) + assert math.dist(position, head) < TIP_TOLERANCE + # Stick up tilts the tool up, which lowers the angle from straight up. + assert level - pitch > math.radians(20) + run(teleop, 6.0, left_y=-1.0) + position, pitch = tip(arm, teleop) + assert math.dist(position, head) < TIP_TOLERANCE + assert pitch - level > math.radians(20) + + +def test_the_right_stick_rolls_the_tool_while_the_tip_stays(teleop, arm): + reach_head(teleop) + roll = teleop.targets['joint_5'] + run(teleop, 2.0, right_x=1.0) + assert abs(teleop.targets['joint_5'] - roll) > math.radians(20) + assert math.dist(tip(arm, teleop)[0], teleop.config.head.position) < TIP_TOLERANCE + + +def test_tilting_moves_the_shoulder_elbow_and_wrist_around_the_tip(teleop, arm): + reach_head(teleop) + before = dict(teleop.targets) + run(teleop, 3.0, left_y=1.0) + moved = [joint for joint in ('joint_2', 'joint_3', 'joint_4') + if abs(teleop.targets[joint] - before[joint]) > math.radians(5)] + assert len(moved) >= 2 + assert math.dist(tip(arm, teleop)[0], teleop.config.head.position) < TIP_TOLERANCE + + +@pytest.mark.parametrize('stick', [1.0, -1.0]) +def test_tilting_stops_at_a_joint_limit_and_names_it_with_the_tip_in_place(teleop, arm, stick): + reach_head(teleop) + run(teleop, 25.0, left_y=stick) + assert teleop.blocked + assert all(name in LIMITS for name in teleop.blocked), teleop.blocked + assert math.dist(tip(arm, teleop)[0], teleop.config.head.position) < TIP_TOLERANCE + for joint, (lower, upper) in LIMITS.items(): + assert lower - 1e-6 <= teleop.targets[joint] <= upper + 1e-6 + stopped = dict(teleop.targets) + run(teleop, 1.0, left_y=stick) + assert max(abs(teleop.targets[joint] - stopped[joint]) for joint in LIMITS) < 1e-6 + assert teleop.blocked + # Letting go clears it, and the other way is open. + run(teleop, 0.5) + assert not teleop.blocked + run(teleop, 1.0, left_y=-stick) + assert max(abs(teleop.targets[joint] - stopped[joint]) for joint in LIMITS) > 0.01 + + +def test_a_stick_that_moves_nothing_reports_nothing_when_it_is_not_pushed(teleop): + reach_head(teleop) + run(teleop, 25.0, left_y=1.0) + run(teleop, 1.0) + assert teleop.blocked == [] + + +def test_centered_sticks_leave_the_arm_alone(teleop): + reach_head(teleop) + held = dict(teleop.targets) + run(teleop, 2.0) + assert max(abs(teleop.targets[joint] - held[joint]) for joint in LIMITS) < 1e-6 + + +def test_the_tip_does_not_drift_over_a_long_wiggle(teleop, arm): + reach_head(teleop) + for _ in range(4): + run(teleop, 2.0, left_y=1.0, right_x=1.0) + run(teleop, 2.0, left_y=-1.0, right_x=-1.0) + assert math.dist(tip(arm, teleop)[0], teleop.config.head.position) < TIP_TOLERANCE / 5 + + +def test_switching_it_off_holds_the_arm_and_gives_the_sticks_back(teleop): + reach_head(teleop) + ok, message = teleop.set_head_mode(False) + assert ok and teleop.head_status()[0] == 'off' + held = dict(teleop.targets) + run(teleop, 1.0) + assert teleop.targets == held + run(teleop, 1.0, left_x=1.0) + assert teleop.targets['joint_1'] != held['joint_1'] + + +@pytest.mark.parametrize('button', ['b', 'y', 'a']) +def test_stop_group_and_home_end_the_mode(teleop, button): + reach_head(teleop) + press(teleop, button) + assert teleop.head_status()[0] == 'off' + + +def test_switching_the_mode_off_with_a_stick_held_waits_for_it_to_centre(teleop): + reach_head(teleop) + run(teleop, 0.5, left_y=1.0) + ok, _ = teleop.set_head_mode(False) + assert ok + held = dict(teleop.targets) + # The same stick would move the shoulder in the active group, which must not happen yet. + run(teleop, 1.0, left_y=1.0) + assert teleop.targets == held + assert 'Center' in teleop.note and teleop.warning + run(teleop, 0.2) + assert not teleop.wait_for_center + run(teleop, 0.5, left_y=1.0) + assert teleop.targets != held + + +def test_switching_the_mode_off_with_the_sticks_centred_waits_for_nothing(teleop): + reach_head(teleop) + ok, _ = teleop.set_head_mode(False) + assert ok and not teleop.wait_for_center + assert 'Chicken head off' in teleop.note + + +def test_the_mode_needs_teleop_enabled_first(params, arm): + teleop = build(params, arm) + ok, message = teleop.set_head_mode(True) + assert not ok and 'Start' in message + assert teleop.head_status()[0] == 'off' + + +def test_a_joint_that_cannot_move_refuses_the_mode(params, arm): + teleop = enabled(build(params, arm, locked={'joint_2': 0.0})) + ok, message = teleop.set_head_mode(True) + assert not ok and 'joint_2' in message + assert teleop.head_status()[0] == 'off' + + +def test_a_head_spot_the_arm_cannot_reach_is_refused(params, arm): + teleop = enabled(build({**params, 'chicken_head.position': [2.0, 0.0, 0.5]}, arm)) + ok, message = teleop.set_head_mode(True) + assert not ok and 'reach' in message + assert teleop.head_status()[0] == 'off' + + +def test_a_mode_with_no_head_settings_is_unavailable(params, arm): + flat = {name: value for name, value in params.items() if not name.startswith('chicken_head.')} + teleop = enabled(build(flat, arm)) + ok, message = teleop.set_head_mode(True) + assert not ok and 'chicken_head' in message + assert teleop.head_status()[0] == 'unavailable' + + +def test_a_mode_without_arm_kinematics_is_unavailable(params): + teleop = ArmTeleop(config_from_parameters(params), LIMITS) + assert teleop.head_status()[0] == 'unavailable' + + +def test_an_approach_that_cannot_make_progress_says_it_is_blocked(params, arm): + class Wall: + """Any move from the start pose goes into something.""" + + def __init__(self, start): + self.start = dict(start) + + def check(self, joints): + return {'wall': 0.1} if any(joints[name] != self.start[name] + for name in LIMITS) else {} + + teleop = enabled(build(params, arm, collision=Wall(HOME))) + ok, _ = teleop.set_head_mode(True) + assert ok + run(teleop, 3.0) + state, message = teleop.head_status() + assert state == 'blocked' and 'wall' in message + assert teleop.targets == HOME or max(abs(teleop.targets[j] - HOME[j]) for j in LIMITS) == 0.0 + + +@pytest.mark.parametrize('change, message', [ + ({'chicken_head.position': [0.3, 0.0]}, 'position'), + ({'chicken_head.position': [0.3, 0.0, float('nan')]}, 'position'), + ({'chicken_head.pitch_deg': float('inf')}, 'pitch'), + ({'chicken_head.axes': ['left_y', 'sideways']}, 'unknown controller inputs'), + ({'chicken_head.axes': ['left_y']}, 'axes'), + ({'chicken_head.scales': [1.0, 2.0]}, 'scales'), +]) +def test_a_bad_head_config_is_refused(params, change, message): + with pytest.raises(ValueError, match=message): + config_from_parameters({**params, **change}) diff --git a/waybionic_teleop/test/test_demo_mode.py b/waybionic_teleop/test/test_demo_mode.py new file mode 100644 index 0000000..b83bb93 --- /dev/null +++ b/waybionic_teleop/test/test_demo_mode.py @@ -0,0 +1,550 @@ +"""Demo mode: the arm moves around by itself, slowly and smoothly, and comes back to its pose.""" + +import math +from pathlib import Path + +import pytest + +from waybionic_teleop.collision import ArmCollision +from waybionic_teleop.gamepad import AXES, BUTTONS +from waybionic_teleop.kinematics import ArmKinematics +from waybionic_teleop.teleop import ArmTeleop, config_from_parameters, DEMO_STATES + +LIMITS = {'joint_1': (-math.pi, math.pi), 'joint_2': (-1.5708, 1.5708), + 'joint_3': (-1.5708, 1.5708), 'joint_4': (-1.5708, 1.5708), + 'joint_5': (-1.5708, 1.5708)} +ARM = tuple(LIMITS) +HOME = dict.fromkeys([*LIMITS, 'tool_grip'], 0.0) +URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' + / 'waybionic_arm.urdf').read_text(encoding='utf-8') +DT = 1.0 / 120.0 +DEG = math.pi / 180.0 + + +def sample(*pressed, **axes): + return [axes.get(name, 0.0) for name in AXES], [int(name in pressed) for name in BUTTONS] + + +def run(teleop, seconds, *pressed, **axes): + for _ in range(round(seconds / DT)): + teleop.update(*sample(*pressed, **axes), dict(teleop.targets), DT) + + +def press(teleop, button): + teleop.update(*sample(button), dict(teleop.targets), DT) + teleop.update(*sample(), dict(teleop.targets), DT) + + +def trace(teleop, seconds, *pressed, **axes): + """Run the teleop and return the arm's targets after each tick.""" + rows = [] + for _ in range(round(seconds / DT)): + teleop.update(*sample(*pressed, **axes), dict(teleop.targets), DT) + rows.append({joint: teleop.targets[joint] for joint in ARM}) + return rows + + +def speeds(rows): + """Return each joint's speed (rad/s) between consecutive ticks.""" + return [{joint: (later[joint] - earlier[joint]) / DT for joint in ARM} + for earlier, later in zip(rows, rows[1:])] + + +def peak_speed(rows): + return max(abs(value) for row in speeds(rows) for value in row.values()) + + +def peak_accel(rows): + velocities = speeds(rows) + return max(abs(later[joint] - earlier[joint]) / DT + for earlier, later in zip(velocities, velocities[1:]) for joint in ARM) + + +def build(params, arm, limits=LIMITS, **options): + options.setdefault('collision', ArmCollision.from_urdf(URDF, 0.0, 0.01)) + return ArmTeleop(config_from_parameters(params), limits, arm, **options) + + +def enabled(teleop, measured=HOME): + teleop.update(*sample('start'), measured, DT) + teleop.update(*sample(), measured, DT) + assert teleop.enabled + return teleop + + +@pytest.fixture +def arm(): + return ArmKinematics.from_urdf(URDF) + + +@pytest.fixture +def params(parameters): + return parameters('xbox_teleop.yaml', 'xbox_teleop') + + +@pytest.fixture +def teleop(params, arm): + return enabled(build(params, arm)) + + +def start(teleop): + ok, message = teleop.set_demo_mode(True) + assert ok, message + + +@pytest.fixture(scope='module') +def whole_demo(parameters): + """Run the demo for its ramp, a whole loop and the return, recording every tick.""" + arm = ArmKinematics.from_urdf(URDF) + teleop = enabled(build(parameters('xbox_teleop.yaml', 'xbox_teleop'), arm)) + settings = teleop.config.demo + start(teleop) + rows, blocked, commands, references = [], [], [], [] + for _ in range(round((settings.ramp + settings.loop) / DT)): + teleop.update(*sample(), dict(teleop.targets), DT) + rows.append({joint: teleop.targets[joint] for joint in ARM}) + commands.append({joint: teleop.command_targets[joint] for joint in ARM}) + references.append(teleop.demo.positions()) + blocked.append(list(teleop.blocked)) + running = len(rows) + teleop.set_demo_mode(False) + for _ in range(round((settings.ramp + 1.0) / DT)): + teleop.update(*sample(), dict(teleop.targets), DT) + rows.append({joint: teleop.targets[joint] for joint in ARM}) + return {'teleop': teleop, 'arm': arm, 'rows': rows, 'running': running, 'blocked': blocked, + 'commands': commands, 'references': references} + + +def test_the_demo_settings_come_from_the_config(teleop): + demo = teleop.config.demo + assert demo.joints == list(ARM) + assert demo.amplitudes == pytest.approx([30 * DEG, 15 * DEG, 25 * DEG, 20 * DEG, 35 * DEG]) + assert demo.cycles == [3, 5, 4, 6, 2] + assert (demo.loop, demo.ramp) == (120.0, 12.0) + assert demo.max_speed == pytest.approx(12 * DEG) + + +def test_demo_mode_is_off_until_it_is_switched_on(teleop): + assert teleop.demo_status() == ('off', '') + assert teleop.demo is None + + +def test_switching_on_needs_teleop_enabled_first(params, arm): + teleop = build(params, arm) + ok, message = teleop.set_demo_mode(True) + assert not ok and 'Press Start' in message + assert teleop.demo_status() == ('off', '') + + +def test_demo_mode_says_what_it_is_doing_in_each_state(teleop): + states = [teleop.demo_status()] + start(teleop) + states.append(teleop.demo_status()) + teleop.set_demo_mode(False) + states.append(teleop.demo_status()) + assert [state for state, _ in states] == ['off', 'running', 'stopping'] + assert set(DEMO_STATES) >= {state for state, _ in states} + assert not states[0][1] and states[1][1] and states[2][1] + + +def test_the_arm_swings_slowly_and_smoothly(whole_demo): + rows = whole_demo['rows'] + limit = whole_demo['teleop'].config.demo.max_speed + assert peak_speed(rows) <= limit + # Slow means a few degrees a second, however long it runs. + assert peak_speed(rows) < 8.0 * DEG + # Smooth means it speeds up and slows down by a few degrees a second, every second. + assert peak_accel(rows) < 4.0 * DEG + + +def test_the_tool_tip_moves_slowly_too(whole_demo): + arm, rows = whole_demo['arm'], whole_demo['rows'] + tips = [arm.forward(row)[0] for row in rows[::6]] + fastest = max(math.dist(earlier, later) for earlier, later in zip(tips, tips[1:])) / (6 * DT) + assert fastest < 0.10 + + +def test_the_arm_follows_the_demo_exactly_and_the_drives_get_the_next_step(whole_demo): + rows, references, commands = (whole_demo[key] for key in ('rows', 'references', 'commands')) + for row, reference in zip(rows, references): + for joint, angle in reference.items(): + assert row[joint] == pytest.approx(angle, abs=1e-9) + # The lookahead the drives are given is where the next tick will put each joint. + for command, row, later in zip(commands, rows, rows[1:]): + for joint in ARM: + assert command[joint] == pytest.approx(later[joint], abs=2e-5) + + +def test_the_arm_leaves_its_pose_without_a_jump(whole_demo): + rows = whole_demo['rows'] + assert max(abs(rows[0][joint]) for joint in ARM) < 1e-6 + # It starts from rest and is still crawling a second later. + assert peak_speed(rows[:120]) < 0.5 * DEG + + +def test_every_joint_swings_about_its_start_pose_within_its_amplitude(whole_demo): + teleop, rows = whole_demo['teleop'], whole_demo['rows'][:whole_demo['running']] + for joint, amplitude in zip(ARM, teleop.config.demo.amplitudes): + angles = [row[joint] for row in rows] + assert max(angles) <= HOME[joint] + amplitude + 1e-9 + assert min(angles) >= HOME[joint] - amplitude - 1e-9 + assert max(angles) - min(angles) > 1.5 * amplitude + + +def test_the_swing_stays_clear_of_every_joint_limit(whole_demo): + margin = whole_demo['teleop'].config.demo.margin + for row in whole_demo['rows']: + for joint, (lower, upper) in LIMITS.items(): + assert lower + margin <= row[joint] <= upper - margin + + +def test_the_swing_never_runs_into_the_table_or_the_base(whole_demo): + assert not any(whole_demo['blocked']) + collision = ArmCollision.from_urdf(URDF, 0.0, 0.01) + for row in whole_demo['rows'][::12]: + assert collision.check({**HOME, **row}) == {} + + +def test_the_arm_comes_back_to_exactly_where_it_started_and_the_mode_ends(whole_demo): + teleop, rows = whole_demo['teleop'], whole_demo['rows'] + assert teleop.demo is None and teleop.demo_status()[0] == 'off' + assert {joint: teleop.targets[joint] for joint in ARM} == {joint: HOME[joint] for joint in ARM} + assert all(value == 0.0 for value in teleop.velocities.values()) + assert teleop.command_targets == teleop.targets + assert 'back where it started' in teleop.note and not teleop.warning + # And it was moving until then, not parked early. + assert max(abs(rows[-250][joint]) for joint in ARM) > 0.0 + + +def test_the_pose_it_comes_back_to_is_wherever_it_started(params, arm): + start_pose = {**HOME, 'joint_1': 0.4, 'joint_3': -0.3, 'joint_4': 0.2} + teleop = enabled(build(params, arm), start_pose) + start(teleop) + run(teleop, 30.0) + assert any(abs(teleop.targets[joint] - start_pose[joint]) > 0.02 for joint in ARM) + teleop.set_demo_mode(False) + run(teleop, 13.0) + assert teleop.demo is None + assert all(teleop.targets[joint] == start_pose[joint] for joint in ARM) + + +def test_switching_off_returns_through_a_stopping_state(teleop): + start(teleop) + run(teleop, 20.0) + ok, message = teleop.set_demo_mode(False) + assert ok and 'stopping' in message + assert teleop.demo_status()[0] == 'stopping' + run(teleop, 6.0) + assert teleop.demo_status()[0] == 'stopping' + run(teleop, 7.0) + assert teleop.demo_status()[0] == 'off' + + +def test_switching_on_again_while_it_is_stopping_carries_on_without_a_jolt(teleop): + start(teleop) + rows = trace(teleop, 15.0) + teleop.set_demo_mode(False) + rows += trace(teleop, 4.0) + ok, message = teleop.set_demo_mode(True) + assert ok and teleop.demo_status()[0] == 'running', message + rows += trace(teleop, 15.0) + assert peak_speed(rows) <= teleop.config.demo.max_speed + assert peak_accel(rows) < 6.0 * DEG + + +@pytest.mark.parametrize('button', ['b', 'start']) +def test_b_and_start_stop_the_demo_at_once_and_hold_the_arm(teleop, button): + start(teleop) + run(teleop, 20.0) + held = dict(teleop.targets) + teleop.update(*sample(button), dict(held), DT) + assert teleop.demo is None and not teleop.enabled + assert teleop.demo_status() == ('off', '') + assert all(value == 0.0 for value in teleop.velocities.values()) + run(teleop, 1.0) + assert teleop.targets == held + + +def test_y_leaves_demo_mode_and_waits_for_the_sticks(teleop): + start(teleop) + run(teleop, 20.0) + held = dict(teleop.targets) + group = teleop.group + teleop.update(*sample('y', left_y=1.0), dict(held), DT) + assert teleop.demo is None and teleop.group != group + assert teleop.wait_for_center + run(teleop, 1.0, left_y=1.0) + assert teleop.targets == held + + +def test_going_home_leaves_demo_mode_and_homes_the_arm(teleop): + start(teleop) + run(teleop, 25.0) + assert max(abs(teleop.targets[joint]) for joint in ARM) > 0.02 + run(teleop, 6.0, 'a') + assert teleop.demo is None + assert max(abs(teleop.targets[joint]) for joint in ARM) < 1e-3 + + +def test_the_sticks_do_nothing_while_it_runs(params, arm): + alone, pushed = enabled(build(params, arm)), enabled(build(params, arm)) + start(alone) + start(pushed) + quiet = trace(alone, 20.0) + busy = trace(pushed, 20.0, left_x=1.0, left_y=-1.0, right_x=1.0, right_y=1.0) + assert busy == quiet + + +def test_the_tool_still_closes_and_opens_with_the_triggers(teleop): + start(teleop) + run(teleop, 1.0, right_trigger=-1.0) + assert teleop.targets['tool_grip'] > 0.5 + + +def test_the_speed_level_slows_the_demo_but_never_speeds_it_up(params, arm): + def pace(*presses): + teleop = enabled(build(params, arm)) + for button in presses: + press(teleop, button) + start(teleop) + return trace(teleop, 40.0) + + normal, up = pace(), pace('dpad_up') + half, fifth = pace('dpad_down'), pace('dpad_down', 'dpad_down') + assert up == normal + assert peak_speed(half) == pytest.approx(peak_speed(normal) / 2.0, rel=0.1) + assert peak_speed(fifth) == pytest.approx(peak_speed(normal) / 5.0, rel=0.15) + + +def test_a_change_of_speed_level_does_not_jolt_the_arm(teleop): + start(teleop) + rows = trace(teleop, 20.0) + rows += trace(teleop, DT, 'dpad_down') + rows += trace(teleop, 20.0) + assert peak_accel(rows) < 4.0 * DEG + + +def test_a_locked_joint_stays_exactly_where_it_is(params, arm): + teleop = enabled(build(params, arm, locked={'joint_2': 0.0})) + start(teleop) + rows = trace(teleop, 40.0) + assert all(row['joint_2'] == 0.0 for row in rows) + assert max(abs(row['joint_3']) for row in rows) > 0.05 + + +def test_a_joint_switched_off_stays_put_while_the_others_swing(params, arm): + teleop = build(params, arm) + assert teleop.set_disabled({'joint_4'}, HOME) is True + enabled(teleop) + start(teleop) + rows = trace(teleop, 40.0) + assert all(row['joint_4'] == 0.0 for row in rows) + assert max(abs(row['joint_1']) for row in rows) > 0.02 + + +def test_it_is_refused_when_no_demo_joint_can_move(params, arm): + wrist = {**params, 'demo.joints': ['joint_4', 'joint_5'], + 'demo.amplitudes_deg': [20.0, 35.0], 'demo.cycles': [6, 2], + 'demo.phases_deg': [70.0, 200.0]} + teleop = enabled(build(wrist, arm, locked={'joint_4': 0.0, 'joint_5': 0.0})) + ok, message = teleop.set_demo_mode(True) + assert not ok and 'locked or switched off' in message + + +def test_a_joint_too_near_a_limit_is_left_out_and_the_others_swing(params, arm): + near = {**HOME, 'joint_3': 85 * DEG} + teleop = enabled(build(params, arm, collision=None), near) + start(teleop) + rows = trace(teleop, 40.0) + assert all(row['joint_3'] == near['joint_3'] for row in rows) + assert max(abs(row['joint_1']) for row in rows) > 0.02 + + +def test_every_joint_too_near_a_limit_refuses_the_demo(params, arm): + near = {**dict.fromkeys(ARM, 85 * DEG), 'joint_1': 175 * DEG, 'tool_grip': 0.0} + teleop = enabled(build(params, arm, collision=None), near) + ok, message = teleop.set_demo_mode(True) + assert not ok and 'room to swing' in message + + +def test_a_swing_with_room_to_one_side_only_stays_inside_the_limits(params, arm): + # 30 degrees from a limit with a ten degree margin leaves 20 degrees, not the full 25. + near = {**HOME, 'joint_3': 60 * DEG} + teleop = enabled(build(params, arm, collision=None), near) + start(teleop) + rows = trace(teleop, 130.0) + margin = teleop.config.demo.margin + assert max(row['joint_3'] for row in rows) <= LIMITS['joint_3'][1] - margin + 1e-9 + assert max(row['joint_3'] for row in rows) > 78 * DEG + # The swing is the same size to either side of where it began. + assert min(row['joint_3'] for row in rows) < 42 * DEG + + +def test_chicken_head_and_demo_mode_refuse_each_other(params, arm): + teleop = enabled(build(params, arm)) + ok, _ = teleop.set_head_mode(True) + assert ok + ok, message = teleop.set_demo_mode(True) + assert not ok and 'Chicken head off first' in message + teleop.set_head_mode(False) + start(teleop) + ok, message = teleop.set_head_mode(True) + assert not ok and 'Demo mode off first' in message + assert teleop.demo is not None and teleop.head is None + + +def test_a_tool_through_the_incision_refuses_the_demo(teleop, monkeypatch): + monkeypatch.setattr(teleop, 'inserted', lambda: True) + ok, message = teleop.set_demo_mode(True) + assert not ok and 'inserted' in message + + +class Wall: + """Stands where the shoulder cannot go further than ``reach`` from where it started.""" + + def __init__(self, reach): + self.reach = reach + + def check(self, joints): + excess = abs(joints['joint_2']) - self.reach + return {'wall': excess} if excess > 0.0 else {} + + +def test_a_swing_that_would_reach_an_obstacle_is_made_smaller_to_fit(params, arm): + teleop = enabled(build(params, arm, collision=Wall(0.1))) + start(teleop) + rows = trace(teleop, 130.0) + assert 0.05 < max(abs(row['joint_2']) for row in rows) <= 0.1 + assert teleop.demo is not None and not teleop.blocked + # Every joint got the same smaller share of its swing. + assert max(abs(row['joint_1']) for row in rows) < 0.4 * 30 * DEG + + +def test_a_swing_with_no_room_at_all_is_refused_and_names_what_is_in_the_way(params, arm): + teleop = enabled(build(params, arm, collision=Wall(-1.0))) + ok, message = teleop.set_demo_mode(True) + assert not ok and 'wall' in message and 'move it away' in message + assert teleop.demo is None + + +def test_something_in_the_way_ends_the_demo_and_holds_the_arm(params, arm): + class Obstacle: + """Appears at the pose the arm has reached, and stops it going on.""" + + def __init__(self): + self.pose = None + + def check(self, joints): + if self.pose is None: + return {} + moved = any(abs(joints[joint] - angle) > 1e-9 for joint, angle in self.pose.items()) + return {'obstacle': 0.1} if moved else {} + + obstacle = Obstacle() + teleop = enabled(build(params, arm, collision=obstacle)) + start(teleop) + run(teleop, 20.0) + obstacle.pose = dict(teleop.targets) + run(teleop, 1 * DT) + assert teleop.demo is None + state, message = teleop.demo_status() + assert state == 'off' and 'Demo stopped' in message and 'obstacle' in message + assert teleop.warning and 'obstacle' in teleop.blocked + assert teleop.targets == obstacle.pose + held = dict(teleop.targets) + run(teleop, 2.0) + assert teleop.targets == held and teleop.enabled + + +def test_a_stopped_demo_keeps_its_reason_until_it_is_switched_on_again(params, arm): + class Obstacle: + armed = False + + def check(self, joints): + return {'obstacle': 0.1} if self.armed and joints['joint_1'] != 0.0 else {} + + obstacle = Obstacle() + teleop = enabled(build(params, arm, collision=obstacle)) + start(teleop) + obstacle.armed = True + run(teleop, 1.0) + assert 'obstacle' in teleop.demo_status()[1] + obstacle.armed = False + start(teleop) + assert teleop.demo_status() == ('running', 'Moving slowly around its start pose; ' + 'B stops it at once') + + +def test_a_demo_that_finishes_with_a_stick_held_waits_for_it_to_centre(teleop): + start(teleop) + run(teleop, 20.0) + teleop.set_demo_mode(False) + run(teleop, 13.5, left_y=1.0) + assert teleop.demo is None and teleop.wait_for_center + held = dict(teleop.targets) + run(teleop, 1.0, left_y=1.0) + assert teleop.targets == held and 'Center' in teleop.note + run(teleop, 0.2) + run(teleop, 0.5, left_y=1.0) + assert teleop.targets != held + + +def test_a_step_of_no_time_changes_nothing(teleop): + start(teleop) + run(teleop, 5.0) + before = dict(teleop.targets) + teleop.update(*sample(), dict(before), 0.0) + assert teleop.targets == before + + +def test_a_joint_switched_off_while_it_runs_stops_teleop_and_the_demo(params, arm): + teleop = enabled(build(params, arm)) + start(teleop) + run(teleop, 5.0) + assert teleop.set_disabled({'joint_3'}, dict(teleop.targets)) + assert not teleop.enabled and teleop.demo is None + + +def test_demo_mode_is_unavailable_without_a_demo_section(params, arm): + without = {name: value for name, value in params.items() if not name.startswith('demo.')} + teleop = enabled(build(without, arm)) + assert teleop.config.demo is None + assert teleop.demo_status()[0] == 'unavailable' + ok, message = teleop.set_demo_mode(True) + assert not ok and 'demo section' in message + + +def test_demo_mode_is_unavailable_when_the_arm_lacks_a_demo_joint(params, arm): + short = {joint: bounds for joint, bounds in LIMITS.items() if joint != 'joint_5'} + teleop = ArmTeleop(config_from_parameters(params), short, None, None) + assert teleop.demo_status()[0] == 'unavailable' + ok, message = teleop.set_demo_mode(True) + assert not ok and 'fits this arm' in message + + +@pytest.mark.parametrize('change, message', [ + ({'demo.amplitudes_deg': [30.0, 15.0]}, 'a phase for each swing'), + ({'demo.joints': []}, 'a phase for each swing'), + ({'demo.joints': ['joint_1', 'joint_1', 'joint_3', 'joint_4', 'joint_5']}, 'different'), + ({'demo.joints': ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'tool_grip']}, 'not the tool'), + ({'demo.loop_s': float('inf')}, 'finite'), + ({'demo.phases_deg': [0.0, 140.0, 250.0, float('nan'), 200.0]}, 'finite'), + ({'demo.amplitudes_deg': [30.0, -15.0, 25.0, 20.0, 40.0]}, 'negative'), + ({'demo.margin_deg': -1.0}, 'negative'), + ({'demo.loop_s': 0.0}, 'positive'), + ({'demo.ramp_s': -3.0}, 'positive'), + ({'demo.cycles': [3, 5, 4, 0, 2]}, 'whole numbers'), + ({'demo.cycles': [3, 5, 4, 6, 2.5]}, 'whole numbers'), + ({'demo.max_speed_deg_s': 90.0}, 'above max_speed_deg_s'), + ({'demo.max_speed_deg_s': 5.0}, 'could go at'), + ({'demo.ramp_s': 2.0}, 'could go at'), + ({'demo.cycles': [3, 5, 4, 6, 20]}, 'could go at'), +]) +def test_a_demo_that_is_badly_set_up_or_too_fast_is_refused(params, change, message): + with pytest.raises(ValueError, match=message): + config_from_parameters({**params, **change}) + + +def test_a_whole_number_of_cycles_that_arrives_as_a_float_is_accepted(params): + config = config_from_parameters({**params, 'demo.cycles': [3.0, 5.0, 4.0, 6.0, 2.0]}) + assert config.demo.cycles == [3, 5, 4, 6, 2] diff --git a/waybionic_teleop/test/test_motion_modes_panel.py b/waybionic_teleop/test/test_motion_modes_panel.py new file mode 100644 index 0000000..47b0978 --- /dev/null +++ b/waybionic_teleop/test/test_motion_modes_panel.py @@ -0,0 +1,51 @@ +"""The RViz motion modes panel and the teleop node agree on every mode's topic and states.""" + +from pathlib import Path +import re + +import pytest + +from waybionic_teleop import chicken_head, demo_mode +from waybionic_teleop.teleop import DEMO_STATES, HEAD_STATES + +SOURCE = (Path(__file__).resolve().parents[2] / 'waybionic_rviz_plugins' / 'src' + / 'mode_model.cpp').read_text(encoding='utf-8') +# The panel's table of each mode, the node's module for it, the message it publishes, and the +# states the node can be in. +MODES = [('chickenHeadSpec', chicken_head, chicken_head.head_message, HEAD_STATES), + ('demoSpec', demo_mode, demo_mode.demo_message, DEMO_STATES)] + + +def spec_text(function): + """Return the part of mode_model.cpp that defines one mode's table.""" + start = SOURCE.index(f'const ModeSpec & {function}()') + return SOURCE[start:SOURCE.index('return spec;', start)] + + +@pytest.mark.parametrize('function, contract, message, states', MODES) +def test_the_panel_reads_the_row_and_topic_and_calls_the_service_the_node_offers( + function, contract, message, states): + table = spec_text(function) + strings = re.findall(r'"([^"]*)"', table.split('{\n {')[0]) + assert contract.ROW == strings[0] + assert [f'/{contract.TOPIC}', f'/{contract.SERVICE}'] == strings[-2:] + + +@pytest.mark.parametrize('function, contract, message, states', MODES) +def test_the_panel_knows_every_state_the_node_publishes_in_the_same_order( + function, contract, message, states): + names = re.findall(r'\{"(\w+)", "[^"]*", (?:true|false), Tone::\w+\}', spec_text(function)) + assert names == list(states) + + +@pytest.mark.parametrize('function, contract, message, states', MODES) +def test_every_state_is_published_as_one_row_with_that_state(function, contract, message, states): + for state in states: + row = message(state, 'Something to say').status[0] + assert row.name == contract.ROW and row.message == 'Something to say' + assert [(item.key, item.value) for item in row.values] == [('state', state)] + + +def test_the_panel_lists_both_modes_and_only_those(): + assert re.findall(r'static const std::vector specs\{([^}]*)\}', SOURCE) == [ + '&chickenHeadSpec(), &demoSpec()'] diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index 4a1d3f0..f9a8fce 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -45,6 +45,7 @@ from waybionic_teleop.sim_drives import SimulatedServo from waybionic_teleop.slcan_bus import SlcanBus from waybionic_teleop.teleop import ArmTeleop, config_from_parameters +from waybionic_teleop.wander import Wander import yaml URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' @@ -2032,3 +2033,76 @@ def test_shutdown_error_waits_for_the_signal_thread_to_shut_rclpy_down( module.main() assert next(running, None) is None assert factory.return_value.destroy_node.call_count == 1 + + +def stopped_drive_states(node, monkeypatch, speed_deg_s, seconds=5.0): + """Hold the base drive still while teleop tells it to move, and return its health states.""" + ready(node) + servo = node.bus.drives[node.map.drives[0].can_id] + clock = [max(node.heard) + 0.1] + monkeypatch.setattr(sim_arm_drives_node.time, 'monotonic', lambda: clock[0]) + velocities = {**dict.fromkeys(node.map.joints, 0.0), 'joint_1': math.radians(speed_deg_s)} + node.on_command(command(node, velocities=velocities, joint_1=math.radians(3.0))) + node.report() + servo.set_test_fault('stalled') + states = [] + for tick in range(1, round(seconds / node.period) + 1): + clock[0] += node.period + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities=velocities, joint_1=math.radians(3.0))) + node.last_tick = clock[0] - node.period + node.tick() + if tick % round(REPORT_PERIOD_S / node.period) == 0: + node.report() + states.append(node.drive_health_states[0]) + return states + + +@pytest.mark.parametrize('speed', [1.0, 5.0, 30.0]) +def test_a_stopped_drive_told_to_move_at_a_walking_pace_or_more_is_called_stalled( + node, monkeypatch, speed): + states = stopped_drive_states(node, monkeypatch, speed) + assert DriveHealthState.STALLED in states + + +@pytest.mark.parametrize('speed', [0.05, 0.2, 0.5]) +def test_a_drive_told_to_move_only_slowly_is_not_called_stalled(node, monkeypatch, speed): + # It would cover less than the stall distance in the stall window even if it moved exactly + # as told, so standing still tells nothing. + states = stopped_drive_states(node, monkeypatch, speed) + assert DriveHealthState.STALLED not in states + assert states and all(state is DriveHealthState.OK for state in states) + + +def test_the_slow_swing_of_demo_mode_never_makes_a_drive_look_stalled( + node, monkeypatch, parameters): + demo = config_from_parameters(parameters('xbox_teleop.yaml', 'xbox_teleop')).demo + joints = [joint for joint in node.map.joints if joint in demo.joints] + wander = demo_wander(demo, joints) + ready(node) + clock = [max(node.heard) + 0.1] + monkeypatch.setattr(sim_arm_drives_node.time, 'monotonic', lambda: clock[0]) + seen = set() + before = dict(wander.positions()) + for tick in range(1, round(40.0 / node.period) + 1): + clock[0] += node.period + wander.advance(node.period, 1.0) + now = wander.positions() + velocities = {joint: (now[joint] - before[joint]) / node.period for joint in joints} + before = now + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities=velocities, **now)) + node.last_tick = clock[0] - node.period + node.tick() + if tick % round(REPORT_PERIOD_S / node.period) == 0: + node.report() + seen.update(state for state in node.drive_health_states if state is not None) + assert node.authorized + assert seen == {DriveHealthState.OK} + + +def demo_wander(demo, joints): + """Return a Wander for demo's swings on the given joints, centred on the zero pose.""" + swings = {joint: (amplitude, cycles, phase) for joint, amplitude, cycles, phase + in zip(demo.joints, demo.amplitudes, demo.cycles, demo.phases) if joint in joints} + return Wander(dict.fromkeys(swings, 0.0), swings, demo.loop, demo.ramp) diff --git a/waybionic_teleop/test/test_wander.py b/waybionic_teleop/test/test_wander.py new file mode 100644 index 0000000..0f9c4c8 --- /dev/null +++ b/waybionic_teleop/test/test_wander.py @@ -0,0 +1,238 @@ +"""The demo's slow wandering: the ramp that starts and stops the swing, and the swing itself.""" + +import math + +import pytest + +from waybionic_teleop.wander import Ramp, TEMPO_RATE, Wander + +DT = 1.0 / 120.0 +JOINTS = ('joint_1', 'joint_2', 'joint_3') +CENTRE = {'joint_1': 0.1, 'joint_2': -0.2, 'joint_3': 0.3} +SWINGS = {'joint_1': (math.radians(30), 3, 0.0), 'joint_2': (math.radians(15), 5, 2.4), + 'joint_3': (math.radians(25), 4, 4.4)} +LOOP, RAMP = 120.0, 12.0 + + +def run(ramp, seconds): + """Step the ramp and return (levels, rates, accels) sampled every tick.""" + levels, rates, accels = [], [], [] + for _ in range(round(seconds / DT)): + levels.append(ramp.step(DT)) + rates.append(ramp.rate) + accels.append(ramp.accel) + return levels, rates, accels + + +def settle(wander, seconds=None, tempo=1.0): + """Advance a wander until its ramp has settled, or for the given seconds.""" + steps = round(seconds / DT) if seconds is not None else 10 ** 6 + for _ in range(steps): + if seconds is None and wander.ramp.settled: + return + wander.advance(DT, tempo) + + +def test_a_ramp_starts_and_ends_at_rest(): + ramp = Ramp(10.0) + ramp.aim(1.0) + levels, rates, accels = run(ramp, 10.0) + assert levels[-1] == 1.0 and rates[-1] == 0.0 and accels[-1] == 0.0 + assert ramp.settled + assert abs(rates[0]) < 1e-3 and abs(accels[0]) < 1e-2 + assert all(later >= earlier for earlier, later in zip(levels, levels[1:])) + + +def test_a_ramp_takes_exactly_its_duration(): + ramp = Ramp(10.0) + ramp.aim(1.0) + levels, _, _ = run(ramp, 9.9) + assert not ramp.settled and levels[-1] < 1.0 + run(ramp, 0.2) + assert ramp.settled and ramp.level == 1.0 + + +def test_a_ramp_peaks_at_the_minimum_jerk_rate(): + ramp = Ramp(10.0) + ramp.aim(1.0) + _, rates, _ = run(ramp, 10.0) + assert max(rates) == pytest.approx(1.875 / 10.0, rel=1e-3) + + +def test_a_ramp_goes_back_down_the_same_way(): + ramp = Ramp(10.0) + ramp.aim(1.0) + run(ramp, 10.0) + ramp.aim(0.0) + levels, rates, _ = run(ramp, 10.0) + assert levels[-1] == 0.0 and ramp.settled + assert min(rates) == pytest.approx(-1.875 / 10.0, rel=1e-3) + assert all(later <= earlier for earlier, later in zip(levels, levels[1:])) + + +@pytest.mark.parametrize('seconds', [0.5, 2.0, 5.0, 8.0, 11.0]) +def test_a_ramp_reversed_part_way_has_no_jump_in_rate_or_acceleration(seconds): + ramp = Ramp(12.0) + ramp.aim(1.0) + run(ramp, seconds) + level, rate, accel = ramp.level, ramp.rate, ramp.accel + ramp.aim(0.0) + levels, rates, accels = run(ramp, 12.1) + assert abs(levels[0] - level) <= abs(rate) * DT * 2 + 1e-6 + assert abs(rates[0] - rate) < 2e-3 + assert abs(accels[0] - accel) < 0.04 + # Every later tick changes the rate by a tiny amount, with no kink anywhere on the way. + assert max(abs(later - earlier) for earlier, later in zip(rates, rates[1:])) < 2e-3 + assert min(levels) >= 0.0 and max(levels) <= 1.0 + assert levels[-1] == 0.0 and ramp.settled + + +def test_a_short_trip_takes_less_time_and_is_not_much_faster_or_sharper_than_a_full_one(): + full = Ramp(12.0) + full.aim(1.0) + _, full_rates, full_accels = run(full, 12.1) + for seconds in (0.5, 2.0, 5.0, 11.9): + ramp = Ramp(12.0) + ramp.aim(1.0) + run(ramp, seconds) + ramp.aim(0.0) + taken = 0.0 + rates, accels = [], [] + while not ramp.settled: + ramp.step(DT) + taken += DT + rates.append(abs(ramp.rate)) + accels.append(abs(ramp.accel)) + assert taken <= 12.0 + DT + assert max(rates) <= 1.3 * max(full_rates) + assert max(accels) <= 3.6 * max(full_accels) + + +def test_stopping_straight_after_starting_is_over_within_a_moment(): + ramp = Ramp(12.0) + ramp.aim(1.0) + run(ramp, 0.3) + ramp.aim(0.0) + run(ramp, 1.5) + assert ramp.settled and ramp.level == 0.0 + + +def test_changing_the_goal_before_it_has_moved_at_all_is_settled_at_once(): + ramp = Ramp(12.0) + ramp.aim(1.0) + ramp.aim(0.0) + run(ramp, 0.5) + assert ramp.settled and ramp.level == 0.0 + + +def test_a_ramp_given_the_goal_it_already_has_keeps_going(): + ramp = Ramp(10.0) + ramp.aim(1.0) + run(ramp, 3.0) + level = ramp.level + ramp.aim(1.0) + run(ramp, 7.1) + assert level < ramp.level == 1.0 and ramp.settled + + +def test_a_ramp_that_is_settled_stays_put(): + ramp = Ramp(10.0, level=1.0) + assert ramp.settled + assert ramp.step(DT) == 1.0 and ramp.rate == 0.0 + + +@pytest.mark.parametrize('duration', [0.0, -1.0, math.inf, math.nan]) +def test_a_ramp_needs_a_positive_finite_duration(duration): + with pytest.raises(ValueError, match='duration'): + Ramp(duration) + + +def test_the_swing_starts_exactly_at_the_centre_pose_and_without_moving(): + wander = Wander(CENTRE, SWINGS, LOOP, RAMP) + assert wander.positions() == CENTRE + wander.advance(DT, 1.0) + for joint in JOINTS: + assert abs(wander.positions()[joint] - CENTRE[joint]) < 1e-6 + + +def test_the_swing_grows_to_its_full_size_and_never_beyond(): + wander = Wander(CENTRE, SWINGS, LOOP, RAMP) + low, high = dict(CENTRE), dict(CENTRE) + for _ in range(round(2 * LOOP / DT)): + wander.advance(DT, 1.0) + for joint, angle in wander.positions().items(): + low[joint], high[joint] = min(low[joint], angle), max(high[joint], angle) + for joint, (amplitude, _, _) in SWINGS.items(): + assert high[joint] <= CENTRE[joint] + amplitude + 1e-9 + assert low[joint] >= CENTRE[joint] - amplitude - 1e-9 + # Over two loops each joint reaches nearly the whole of its swing. + assert high[joint] - low[joint] > 1.9 * amplitude + + +def test_the_whole_motion_repeats_every_loop_once_it_has_grown(): + wander = Wander(CENTRE, SWINGS, LOOP, RAMP) + settle(wander) + first = wander.positions() + settle(wander, LOOP) + again = wander.positions() + for joint in JOINTS: + assert again[joint] == pytest.approx(first[joint], abs=1e-9) + + +def test_the_motion_does_not_come_back_to_where_it_began_part_way_through_a_loop(): + wander = Wander(CENTRE, SWINGS, LOOP, RAMP) + settle(wander) + start = wander.positions() + for fraction in (0.5, 0.25): + probe = Wander(CENTRE, SWINGS, LOOP, RAMP) + settle(probe) + settle(probe, LOOP * fraction) + pose = probe.positions() + assert max(abs(pose[joint] - start[joint]) for joint in JOINTS) > math.radians(5.0) + + +def test_stopping_returns_every_joint_to_the_centre_pose_exactly(): + wander = Wander(CENTRE, SWINGS, LOOP, RAMP) + settle(wander, 40.0) + assert not wander.finished + wander.ramp.aim(0.0) + assert not wander.finished + for _ in range(round((RAMP + 1.0) / DT)): + wander.advance(DT, 1.0) + assert wander.finished + assert wander.positions() == CENTRE + + +def test_slowing_the_clock_slows_the_swing_and_the_start_alike(): + def peak(tempo, seconds): + wander = Wander(CENTRE, SWINGS, LOOP, RAMP, tempo=tempo) + before, fastest = wander.positions(), 0.0 + for _ in range(round(seconds / DT)): + wander.advance(DT, tempo) + now = wander.positions() + fastest = max(fastest, max(abs(now[joint] - before[joint]) for joint in JOINTS) / DT) + before = now + return fastest, wander.ramp.settled + + full, full_settled = peak(1.0, 14.0) + half, half_settled = peak(0.5, 14.0) + assert full_settled and not half_settled + assert half == pytest.approx(full / 2.0, rel=0.1) + + +def test_the_clock_changes_its_pace_gradually(): + wander = Wander(CENTRE, SWINGS, LOOP, RAMP) + paces = [] + for _ in range(round(6.0 / DT)): + wander.advance(DT, 0.2) + paces.append(wander.tempo) + assert paces[0] == pytest.approx(1.0 - TEMPO_RATE * DT) + assert all(abs(later - earlier) <= TEMPO_RATE * DT + 1e-12 + for earlier, later in zip(paces, paces[1:])) + assert paces[-1] == pytest.approx(0.2) + + +@pytest.mark.parametrize('loop', [0.0, -5.0, math.inf]) +def test_a_wander_needs_a_positive_finite_loop(loop): + with pytest.raises(ValueError, match='loop'): + Wander(CENTRE, SWINGS, loop, RAMP) diff --git a/waybionic_teleop/test/test_xbox_teleop_node.py b/waybionic_teleop/test/test_xbox_teleop_node.py index a8b568c..bfcf988 100644 --- a/waybionic_teleop/test/test_xbox_teleop_node.py +++ b/waybionic_teleop/test/test_xbox_teleop_node.py @@ -4,12 +4,13 @@ from pathlib import Path import time -from diagnostic_msgs.msg import DiagnosticArray +from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus import pytest import rclpy from rclpy.parameter import Parameter from sensor_msgs.msg import JointState, Joy from std_msgs.msg import Bool, String +from std_srvs.srv import SetBool from waybionic_teleop import joint_control, xbox_teleop_node from waybionic_teleop.gamepad import AXES, BUTTONS @@ -336,3 +337,191 @@ def test_the_state_row_names_the_joints_that_are_off(node, monkeypatch): node.report() row = next(item for item in diagnostics[-1].status if item.name == 'teleop.state') assert row.message.startswith('Joints off: joint_1, joint_3; ') + + +def head_rows(published): + """Return {state: message} for the chicken head rows the node has published.""" + return {next(item.value for item in message.status[0].values if item.key == 'state'): + message.status[0].message for message in published} + + +def test_the_head_service_switches_the_mode_and_publishes_its_state(node, monkeypatch): + published = [] + monkeypatch.setattr(node.head_publisher, 'publish', published.append) + ready(node) + response = node.on_head(SetBool.Request(data=True), SetBool.Response()) + assert response.success and 'moving' in response.message + assert node.teleop.head_status()[0] == 'approach' + assert 'approach' in head_rows(published) + response = node.on_head(SetBool.Request(data=False), SetBool.Response()) + assert response.success and node.teleop.head_status()[0] == 'off' + assert 'off' in head_rows(published) + + +def test_the_head_service_says_why_it_cannot_start(node, monkeypatch): + published = [] + monkeypatch.setattr(node.head_publisher, 'publish', published.append) + node.load(String(data=URDF)) + response = node.on_head(SetBool.Request(data=True), SetBool.Response()) + assert not response.success and 'Start' in response.message + assert node.teleop.head_status()[0] == 'off' + assert published and published[-1].status[0].level == DiagnosticStatus.OK + + +def test_the_head_service_without_a_robot_description_says_so(node, monkeypatch): + published = [] + monkeypatch.setattr(node.head_publisher, 'publish', published.append) + response = node.on_head(SetBool.Request(data=True), SetBool.Response()) + assert not response.success and 'robot_description' in response.message + assert 'unavailable' in head_rows(published) + assert published[-1].status[0].level == DiagnosticStatus.WARN + + +def test_the_head_state_is_reported_with_the_other_rows(node, monkeypatch): + published = [] + monkeypatch.setattr(node.head_publisher, 'publish', published.append) + ready(node) + node.report() + assert head_rows(published) == {'off': ''} + + +def test_the_label_and_diagnostics_show_chicken_head(node, monkeypatch): + rows = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', rows.append) + ready(node) + node.on_head(SetBool.Request(data=True), SetBool.Response()) + assert node.summary(True).startswith('HEAD\n') + node.report() + by_name = {row.name: row for row in rows[-1].status} + assert by_name['teleop.group'].values[0].value == 'chicken head' + assert 'tip' in by_name['teleop.group'].message + assert 'deg/s' in by_name['teleop.speed'].message + + +def test_stopping_teleop_ends_the_mode_and_the_row_follows(node, monkeypatch): + published = [] + monkeypatch.setattr(node.head_publisher, 'publish', published.append) + ready(node) + node.on_head(SetBool.Request(data=True), SetBool.Response()) + tick(node, 'b') + assert not node.teleop.enabled + node.report() + assert list(head_rows(published[-1:])) == ['off'] + + +def demo_rows(published): + """Return {state: message} for the demo rows the node has published.""" + return {next(item.value for item in message.status[0].values if item.key == 'state'): + message.status[0].message for message in published} + + +def test_the_demo_service_switches_the_mode_and_publishes_its_state(node, monkeypatch): + published = [] + monkeypatch.setattr(node.demo_publisher, 'publish', published.append) + ready(node) + response = node.on_demo(SetBool.Request(data=True), SetBool.Response()) + assert response.success and 'slowly' in response.message + assert node.teleop.demo_status()[0] == 'running' + assert 'running' in demo_rows(published) + response = node.on_demo(SetBool.Request(data=False), SetBool.Response()) + assert response.success and 'stopping' in response.message + assert node.teleop.demo_status()[0] == 'stopping' + assert 'stopping' in demo_rows(published) + + +def test_the_demo_service_says_why_it_cannot_start(node, monkeypatch): + published = [] + monkeypatch.setattr(node.demo_publisher, 'publish', published.append) + node.load(String(data=URDF)) + response = node.on_demo(SetBool.Request(data=True), SetBool.Response()) + assert not response.success and 'Start' in response.message + assert node.teleop.demo_status()[0] == 'off' + assert published and published[-1].status[0].level == DiagnosticStatus.OK + + +def test_the_demo_service_without_a_robot_description_says_so(node, monkeypatch): + published = [] + monkeypatch.setattr(node.demo_publisher, 'publish', published.append) + response = node.on_demo(SetBool.Request(data=True), SetBool.Response()) + assert not response.success and 'robot_description' in response.message + assert 'unavailable' in demo_rows(published) + assert published[-1].status[0].level == DiagnosticStatus.WARN + + +def test_the_demo_state_is_reported_with_the_other_rows(node, monkeypatch): + published = [] + monkeypatch.setattr(node.demo_publisher, 'publish', published.append) + ready(node) + node.report() + assert demo_rows(published) == {'off': ''} + + +def test_the_demo_row_is_a_warning_only_when_there_is_something_to_warn_about(): + from waybionic_teleop import demo_mode + levels = {(state, bool(message)): demo_mode.demo_message(state, message).status[0].level + for state, message in [('off', ''), ('off', 'Demo stopped: blocked by x'), + ('running', 'Moving'), ('stopping', 'Returning'), + ('unavailable', 'No model')]} + assert levels == {('off', False): DiagnosticStatus.OK, ('off', True): DiagnosticStatus.WARN, + ('running', True): DiagnosticStatus.OK, + ('stopping', True): DiagnosticStatus.OK, + ('unavailable', True): DiagnosticStatus.WARN} + + +def test_the_label_and_diagnostics_show_demo_mode(node, monkeypatch): + rows = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', rows.append) + ready(node) + node.on_demo(SetBool.Request(data=True), SetBool.Response()) + assert node.summary(True).startswith('DEMO\n') + node.report() + by_name = {row.name: row for row in rows[-1].status} + assert by_name['teleop.group'].values[0].value == 'demo' + assert 'slowly' in by_name['teleop.group'].message + assert 'deg/s max' in by_name['teleop.speed'].message + assert 'does not speed it up' in by_name['teleop.speed'].message + assert 'moving slowly' in by_name['teleop.state'].message + node.teleop.note = '' + node.report() + state = next(row for row in rows[-1].status if row.name == 'teleop.state') + assert 'leaves demo mode' in state.message + + +def test_the_node_streams_the_demo_to_the_drives_slowly_and_smoothly(node, monkeypatch): + commands = [] + monkeypatch.setattr(node.command_publisher, 'publish', commands.append) + ready(node) + start = dict(node.teleop.targets) + node.on_demo(SetBool.Request(data=True), SetBool.Response()) + for _ in range(round(30.0 / node.config.period)): + tick(node, elapsed=node.config.period) + last = dict(zip(commands[-1].name, commands[-1].position)) + assert any(abs(last[joint] - start[joint]) > 0.01 for joint in node.teleop.kinematics.joints) + cap = node.config.demo.max_speed + assert max(abs(speed) for command in commands for speed in command.velocity) <= cap + 1e-9 + assert node.teleop.enabled and node.teleop.demo is not None + + +def test_stopping_teleop_ends_demo_mode_and_the_row_follows(node, monkeypatch): + published = [] + monkeypatch.setattr(node.demo_publisher, 'publish', published.append) + ready(node) + node.on_demo(SetBool.Request(data=True), SetBool.Response()) + tick(node, 'b') + assert not node.teleop.enabled and node.teleop.demo is None + node.report() + assert list(demo_rows(published[-1:])) == ['off'] + + +def test_losing_the_controller_ends_demo_mode_and_holds_the_arm(node, monkeypatch): + commands = [] + monkeypatch.setattr(node.command_publisher, 'publish', commands.append) + ready(node) + node.on_demo(SetBool.Request(data=True), SetBool.Response()) + for _ in range(120): + tick(node, elapsed=node.config.period) + assert node.teleop.demo is not None + node.joy_time = time.monotonic() - node.timeout - 0.1 + node.tick() + assert not node.teleop.enabled and node.teleop.demo is None + assert not any(commands[-1].velocity) diff --git a/waybionic_teleop/waybionic_teleop/chicken_head.py b/waybionic_teleop/waybionic_teleop/chicken_head.py new file mode 100644 index 0000000..0fb430c --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/chicken_head.py @@ -0,0 +1,25 @@ +""" +Chicken head mode's state, as the Xbox teleop node publishes it on ``arm/chicken_head``. + +The topic carries a latched DiagnosticArray with one row, ``chicken_head``. Its message says what +is happening or why the mode cannot start, and its ``state`` value is one of ``off``, +``approach`` (the tip is moving to the head spot), ``hold`` (the tip is held while the sticks tilt +and roll the tool), ``blocked`` (the way to the head spot is blocked) or ``unavailable``. The node +serves ``arm/chicken_head/set_enabled`` (std_srvs/SetBool) to switch the mode on or off, and +answers with why it cannot start, for example before Start has been pressed. The RViz chicken head +panel reads the topic and calls the service. +""" + +from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue + +TOPIC = 'arm/chicken_head' +SERVICE = 'arm/chicken_head/set_enabled' +ROW = 'chicken_head' +OFF, APPROACH, HOLD, BLOCKED, UNAVAILABLE = 'off', 'approach', 'hold', 'blocked', 'unavailable' + + +def head_message(state, message): + """Return the latched message for a state and what to tell the operator.""" + level = DiagnosticStatus.OK if state in (OFF, APPROACH, HOLD) else DiagnosticStatus.WARN + return DiagnosticArray(status=[DiagnosticStatus( + name=ROW, level=level, message=message, values=[KeyValue(key='state', value=state)])]) diff --git a/waybionic_teleop/waybionic_teleop/demo_mode.py b/waybionic_teleop/waybionic_teleop/demo_mode.py new file mode 100644 index 0000000..6b2b5c4 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/demo_mode.py @@ -0,0 +1,27 @@ +""" +Demo mode's state, as the Xbox teleop node publishes it on ``arm/demo``. + +The topic carries a latched DiagnosticArray with one row, ``demo``. Its message says what is +happening or why the mode stopped by itself, and its ``state`` value is one of ``off``, +``running`` (the arm is moving slowly around the pose it started from), ``stopping`` (it is +returning to that pose) or ``unavailable``. The row is a warning when the mode cannot be used or +stopped because something was in the way. The node serves ``arm/demo/set_enabled`` +(std_srvs/SetBool) to switch the mode on or off, and answers with why it cannot start, for example +before Start has been pressed. The RViz motion modes panel reads the topic and calls the service. +""" + +from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue + +TOPIC = 'arm/demo' +SERVICE = 'arm/demo/set_enabled' +ROW = 'demo' +OFF, RUNNING, STOPPING, UNAVAILABLE = 'off', 'running', 'stopping', 'unavailable' + + +def demo_message(state, message): + """Return the latched message for a state and what to tell the operator.""" + # An off mode only has something to say when it stopped itself. + warning = state == UNAVAILABLE or (state == OFF and bool(message)) + level = DiagnosticStatus.WARN if warning else DiagnosticStatus.OK + return DiagnosticArray(status=[DiagnosticStatus( + name=ROW, level=level, message=message, values=[KeyValue(key='state', value=state)])]) diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index 0865c1f..afab31b 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -72,6 +72,10 @@ REPLY_TIMEOUT_S = 0.5 REPORT_PERIOD_S = 0.5 +# A drive is judged stalled only while it is told to move this many times the distance that +# counts as moving, in the time that is allowed for it. Told to go slower, it covers less than that +# distance even when it does exactly what it is told, as a joint does at the end of a slow swing. +STALL_MARGIN = 1.5 # The carrier reports ten times a second. CARRIER_TIMEOUT_S = 0.5 # Zeroing waits for the joint commands to stop, so teleop must be disabled first. @@ -137,7 +141,7 @@ def __init__(self, **kwargs): self.command_timeout = float(params.get('command_timeout_s', 0.5)) self.following_error = int(params.get('following_error_counts', 4096)) self.following_ticks = int(params.get('following_error_ticks', 12)) - health_thresholds = DriveHealthThresholds( + self.health_thresholds = health_thresholds = DriveHealthThresholds( following_error_degrees=float(params['health_following_error_degrees']), stall_movement_degrees=float(params['health_stall_movement_degrees']), stall_duration_seconds=float(params['health_stall_duration_seconds']), @@ -1030,10 +1034,15 @@ def report(self): servo = self.bus.drives.get(drive.can_id) if servo is not None: enabled = enabled and servo.enabled + # The drive's output turns at its shaft speed divided by the gear ratio. + output_speed = health_motor_rates[index] * 6.0 / drive.gear_ratio + stall_window = self.health_thresholds.stall_duration_seconds + told_to_move = output_speed * stall_window >= ( + STALL_MARGIN * self.health_thresholds.stall_movement_degrees) self.drive_health_states[index] = self.drive_health_monitors[index].evaluate( target_position=target * counts_to_joint_degrees, encoder_position=count * counts_to_joint_degrees, - motion_commanded=self.authorized and health_motor_rates[index] > 0.0, + motion_commanded=self.authorized and told_to_move, enabled=enabled, reply_age_seconds=now - heard, now_seconds=now, diff --git a/waybionic_teleop/waybionic_teleop/teleop.py b/waybionic_teleop/waybionic_teleop/teleop.py index f984798..57c9f55 100644 --- a/waybionic_teleop/waybionic_teleop/teleop.py +++ b/waybionic_teleop/waybionic_teleop/teleop.py @@ -1,9 +1,11 @@ """Turn Xbox controller input into arm joint targets (pure logic, no ROS).""" from dataclasses import dataclass +import itertools import math from waybionic_teleop.gamepad import AXIS, BUTTON +from waybionic_teleop.wander import RAMP_PEAK, Wander ACTIONS = ('enable', 'stop', 'group', 'home', 'faster', 'slower', 'lock', 'tilt_up', 'tilt_down') CARTESIAN_AXES = ('x', 'y', 'z', 'roll') @@ -16,6 +18,27 @@ INCISION_LOST = ('The tool is off the incision point; press Y, withdraw it in another group, ' 'then choose the incision group again') INCISION_HELD = 'The tool is inserted; withdraw it to the incision point before pressing Y' +# Chicken head mode. The tip is held at a spot while the sticks tilt and roll the tool. +HEAD_ARRIVED = 1e-6 +# The share of a drift of the held tip that each step takes back, so rounding never builds up. +HEAD_PULL = 0.5 +# An approach that has made no progress for this long is reported as blocked. +HEAD_BLOCKED_S = 1.5 +# A tilt or roll that is asked for, but gets less than this share of its step, is stopped by a +# limit, though the kinematics does not always say which. +HEAD_STALLED = 1e-3 +HEAD_NEAR_LIMIT = math.radians(2.0) +HEAD_STATES = ('off', 'approach', 'hold', 'blocked', 'unavailable') +HEAD_UNAVAILABLE = ('Chicken head needs the arm model and a chicken_head section in ' + 'xbox_teleop.yaml') +# Demo mode. The arm swings slowly about the pose it started from, and comes back to it. +DEMO_STATES = ('off', 'running', 'stopping', 'unavailable') +DEMO_UNAVAILABLE = 'Demo mode needs a demo section in xbox_teleop.yaml that fits this arm' +# The shares of its swing that demo mode tries, biggest first, until the extremes of the swing +# are clear of the table and the base. +DEMO_SCALES = (1.0, 0.6, 0.35) +WAIT_NOTE = 'Center motion controls before moving in the new group' +HAND_BACK_NOTE = 'Center motion controls to take over from the mode that just ended' INCISION_JOINT_OFF = ('A joint is switched off with the tool through the incision point; switch ' 'it back on in Joint control to withdraw the tool') @@ -24,6 +47,24 @@ def clamp(value, low, high): return min(max(value, low), high) +def axis_words(axis): + """Return what to call a controller axis, for example 'left stick' for 'left_y'.""" + side, _, kind = axis.rpartition('_') + return f'{side} stick' if kind in ('x', 'y') else axis.replace('_', ' ') + + +@dataclass +class HeadMode: + """Chicken head mode while it is on: approaching its goal joints, then holding the tip.""" + + goal: dict + # The tip position being held, once the tool has arrived there. + anchor: tuple = None + # How fast the joint furthest from its goal is going (rad/s), and how long it has been stuck. + rate: float = 0.0 + stuck: float = 0.0 + + @dataclass class Group: """Joints that share the sticks; each joint follows one axis with a signed gain.""" @@ -41,6 +82,39 @@ def describe(self): return ', '.join(f'{axis} {move}' for axis, move in zip(self.axes, moves)) +@dataclass +class HeadConfig: + """Where chicken head mode holds the tool tip, and the sticks that tilt and roll the tool.""" + + # The tip in the base frame (m), and the tool axis angle from straight up (rad). + position: tuple + pitch: float + tilt_axis: str + roll_axis: str + tilt_scale: float + roll_scale: float + + +@dataclass +class DemoConfig: + """How demo mode swings the arm's joints about the pose it starts from.""" + + joints: list + # Per joint: how far it swings each way (rad), whole swings per loop, and where in its swing + # it starts (rad). + amplitudes: list + cycles: list + phases: list + # Seconds of demo time for one loop, and for the swing to grow or shrink. + loop: float + ramp: float + # How far a joint stays from its limits, and the least swing worth making (rad). + margin: float + min_swing: float + # The fastest any joint may go (rad/s). + max_speed: float + + @dataclass class TeleopConfig: """Controller mapping and motion limits from config/xbox_teleop.yaml.""" @@ -62,6 +136,39 @@ class TeleopConfig: speed_level: int deadzone: float home_gain: float + head: HeadConfig = None + demo: DemoConfig = None + + +def head_from_parameters(params): + """Build the HeadConfig from the chicken_head parameters, or None if there are none.""" + if 'chicken_head.position' not in params: + return None + axes, scales = params['chicken_head.axes'], params['chicken_head.scales'] + if len(axes) != 2 or len(scales) != 2: + raise ValueError('chicken_head axes and scales need a tilt and a roll entry') + return HeadConfig( + position=tuple(float(value) for value in params['chicken_head.position']), + pitch=math.radians(float(params['chicken_head.pitch_deg'])), + tilt_axis=axes[0], roll_axis=axes[1], + tilt_scale=float(scales[0]), roll_scale=float(scales[1])) + + +def demo_from_parameters(params): + """Build the DemoConfig from the demo parameters, or None if there are none.""" + if 'demo.joints' not in params: + return None + return DemoConfig( + joints=list(params['demo.joints']), + amplitudes=[math.radians(float(value)) for value in params['demo.amplitudes_deg']], + # A whole number that arrived as a float is still a whole number. + cycles=[int(value) if isinstance(value, float) and value.is_integer() else value + for value in params['demo.cycles']], + phases=[math.radians(float(value)) for value in params['demo.phases_deg']], + loop=float(params['demo.loop_s']), ramp=float(params['demo.ramp_s']), + margin=math.radians(float(params['demo.margin_deg'])), + min_swing=math.radians(float(params['demo.min_swing_deg'])), + max_speed=math.radians(float(params['demo.max_speed_deg_s']))) def config_from_parameters(params): @@ -91,7 +198,9 @@ def config_from_parameters(params): speed_levels=[float(level) for level in params['speed_levels']], speed_level=int(params['initial_speed_level']), deadzone=float(params['deadzone']), - home_gain=float(params['home_gain'])) + home_gain=float(params['home_gain']), + head=head_from_parameters(params), + demo=demo_from_parameters(params)) except KeyError as missing: raise ValueError(f'missing teleop parameter {missing}') from None check_config(config) @@ -122,8 +231,20 @@ def check_config(config): raise ValueError(f'group {group.name} mode must be joint, cartesian or incision') elif not len(group.joints) == len(group.axes) == len(group.scales): raise ValueError(f'group {group.name} needs one axis and scale per joint') + head = config.head + if head is not None: + if len(head.position) != 3 or not all(math.isfinite(value) for value in head.position): + raise ValueError('chicken_head position must be three finite numbers (x, y, z in m)') + if not math.isfinite(head.pitch): + raise ValueError('chicken_head pitch_deg must be finite') + if any(not -1.0 <= scale <= 1.0 for scale in (head.tilt_scale, head.roll_scale)): + raise ValueError('chicken_head scales must be between -1 and 1') + if config.demo is not None: + check_demo(config, config.demo) unknown = [name for name in [axis for group in config.groups for axis in group.axes] - + [config.tool_close_axis, config.tool_open_axis] if name not in AXIS] + + [config.tool_close_axis, config.tool_open_axis] + + ([head.tilt_axis, head.roll_axis] if head is not None else []) + if name not in AXIS] unknown += [name for name in config.buttons.values() if name not in BUTTON] if unknown: raise ValueError('unknown controller inputs: ' + ', '.join(map(str, unknown))) @@ -133,6 +254,36 @@ def check_config(config): raise ValueError('tool_limits must be [open, closed] with open < closed') +def check_demo(config, demo): + """Raise ValueError unless demo mode's swings are usable and slow enough.""" + if not demo.joints or len({len(demo.joints), len(demo.amplitudes), len(demo.cycles), + len(demo.phases)}) != 1: + raise ValueError('demo needs a joint, an amplitude, a cycle count and a phase for ' + 'each swing') + if len(set(demo.joints)) != len(demo.joints) or config.tool_joint in demo.joints: + raise ValueError('demo joints must be different arm joints, not the tool') + numbers = [*demo.amplitudes, *demo.phases, demo.loop, demo.ramp, demo.margin, demo.min_swing, + demo.max_speed] + if any(not math.isfinite(number) for number in numbers): + raise ValueError('demo settings must be finite numbers') + if any(amplitude < 0 for amplitude in demo.amplitudes) or demo.margin < 0: + raise ValueError('demo amplitudes_deg and margin_deg must not be negative') + if any(value <= 0 for value in (demo.loop, demo.ramp, demo.min_swing, demo.max_speed)): + raise ValueError('demo loop_s, ramp_s, min_swing_deg and max_speed_deg_s must be positive') + if any(isinstance(cycles, bool) or not isinstance(cycles, int) or cycles < 1 + for cycles in demo.cycles): + raise ValueError('demo cycles must be whole numbers of at least 1') + if demo.max_speed > config.max_speed: + raise ValueError('demo max_speed_deg_s must not be above max_speed_deg_s') + for joint, amplitude, cycles in zip(demo.joints, demo.amplitudes, demo.cycles): + # The swing's own speed, plus the swing growing or shrinking over the ramp. + fastest = amplitude * (2.0 * math.pi * cycles / demo.loop + RAMP_PEAK / demo.ramp) + if fastest > demo.max_speed: + raise ValueError( + f'demo {joint} could go at {math.degrees(fastest):.1f} deg/s, above ' + f'max_speed_deg_s {math.degrees(demo.max_speed):.1f}') + + class ArmTeleop: """Hold joint targets and move them with the active group's sticks while enabled.""" @@ -185,7 +336,19 @@ def __init__(self, config, limits, kinematics=None, collision=None, locked=None) # Whether the tool was out of the body when it last left the incision group. self.withdrawn = True self.held = set() + # The sticks and triggers in the last controller sample, for a mode that ends between + # samples. + self.last_axes = () self.wait_for_center = False + self.wait_note = WAIT_NOTE + # Chicken head mode, while it is on: see set_head_mode. + self.head = None + # Demo mode, while it is on: a Wander. See set_demo_mode. + self.demo = None + # Why demo mode last stopped by itself, until it is switched on again. + self.demo_ended = '' + self.demo_misfit = config.demo is None or any( + joint not in self.limits for joint in config.demo.joints) self.blocked = [] self.note = 'Press Start (Xbox Menu button) to enable' self.warning = False @@ -258,6 +421,7 @@ def linear_speed(self): def update(self, axes, buttons, measured, dt): """Apply one controller sample; return True when the targets should be sent.""" + self.last_axes = axes held = {name for name, index in BUTTON.items() if index < len(buttons) and buttons[index]} pressed = {action for action, name in self.config.buttons.items() if name in held - self.held} @@ -277,7 +441,7 @@ def update(self, axes, buttons, measured, dt): return False if self.wait_for_center: if self.motion_input_held(axes): - self.note = 'Center motion controls before moving in the new group' + self.note = self.wait_note self.warning = True return True self.wait_for_center = False @@ -293,11 +457,14 @@ def change_group(self): self.note, self.warning = INCISION_HELD, True return self.withdrawn = self.incision_offset(self.targets)[1] <= INSERTED + self.end_head() + self.end_demo() self.group = (self.group + 1) % len(self.groups) self.stop_cartesian() self.velocities = dict.fromkeys(self.limits, 0.0) self.command_targets = dict(self.targets) self.wait_for_center = True + self.wait_note = WAIT_NOTE if self.active_group.mode == 'incision' and self.incision is not None: withdrawn = self.withdrawn or self.incision_offset(self.targets)[1] <= INSERTED # Keep the incision point while the tool axis still passes it. Otherwise only a @@ -305,6 +472,12 @@ def change_group(self): if not self.align_incision() and withdrawn: self.incision = None + def hand_back(self): + """After a mode ends, hold the arm until the controls are centred, if they are held.""" + if self.motion_input_held(self.last_axes): + self.wait_for_center = True + self.wait_note = HAND_BACK_NOTE + def motion_input_held(self, axes): config = self.config sticks = {axis for group in config.groups for axis in group.axes} @@ -340,12 +513,16 @@ def enable(self, measured, axes): self.pin_locked() self.stop_cartesian() self.wait_for_center = False + self.head = None + self.demo, self.demo_ended = None, '' self.enabled, self.note, self.warning = True, '', False if self.active_group.mode == 'incision' and self.incision is not None: self.align_incision() def disable(self, measured, note, warning=False): self.enabled, self.note, self.warning = False, note, warning + self.head = None + self.demo, self.demo_ended = None, '' self.velocities = dict.fromkeys(self.limits, 0.0) self.stop_cartesian() self.wait_for_center = False @@ -372,11 +549,18 @@ def move(self, axes, homing, dt): # Going home would drag the tool sideways through the incision. incision = self.active_group.mode == 'incision' if homing and not incision: + self.end_head() + self.end_demo() self.stop_cartesian() for joint, (lower, upper) in self.limits.items(): if joint != config.tool_joint and self.movable(joint): error = clamp(0.0, lower, upper) - self.targets[joint] desired[joint] = clamp(config.home_gain * error, -self.speed, self.speed) + elif self.head is not None: + self.head_step(axes, dt) + desired = {config.tool_joint: 0.0} + elif self.demo is not None: + desired.update(self.demo_step(dt)) elif self.active_group.mode == 'cartesian': self.jog(axes, dt) desired = {config.tool_joint: 0.0} @@ -414,6 +598,13 @@ def move(self, axes, homing, dt): self.command_targets[joint] = clamp( target + velocity * config.period, min(lower, target), max(upper, target)) self.avoid_collisions(before) + if self.head is not None and self.head.anchor is None: + # An approach that a contact keeps stopping starts again slowly, and is reported. + self.head.stuck = self.head.stuck + dt if self.blocked else 0.0 + if self.blocked: + self.head.rate = 0.0 + if self.demo is not None: + self.demo_settle() self.pin_locked() def avoid_collisions(self, before): @@ -479,6 +670,283 @@ def jog(self, axes, dt): future = after self.command_targets.update(future) + def head_status(self): + """Return chicken head mode's state, one of HEAD_STATES, and a line saying why.""" + if self.kinematics is None or self.config.head is None: + return 'unavailable', HEAD_UNAVAILABLE + head = self.head + if head is None: + return 'off', '' + if head.anchor is not None: + settings = self.config.head + return 'hold', (f'Holding the tip in place: the {axis_words(settings.tilt_axis)} ' + f'tilts the tool, the {axis_words(settings.roll_axis)} rolls it') + if head.stuck >= HEAD_BLOCKED_S: + return 'blocked', ('The way to the head position is blocked by ' + + ', '.join(self.blocked or ['something'])) + return 'approach', 'Moving the tip to the head position' + + def head_problem(self): + """Return why chicken head mode cannot start now, or '' if it can; set head_goal.""" + if self.kinematics is None or self.config.head is None: + return HEAD_UNAVAILABLE + if not self.enabled: + return 'Press Start (Xbox Menu button) first, then switch Chicken head on' + if self.demo is not None: + return 'Switch Demo mode off first' + if self.inserted(): + return INCISION_HELD + stuck = [joint for joint in self.kinematics.joints if not self.movable(joint)] + if stuck: + return (f'{", ".join(stuck)} cannot move (locked or switched off); chicken head ' + 'needs every arm joint') + kinematics, head = self.kinematics, self.config.head + roll = kinematics.joints[4] + arm = {name: bounds for name, bounds in self.limits.items() + if name in kinematics.joints and name != roll} + goal = kinematics.inverse(head.position, head.pitch, self.targets[roll], self.targets, arm) + if goal is None: + return 'The head position is out of reach for the arm and its joint limits' + self.head_goal = goal + return '' + + def set_head_mode(self, enabled): + """Switch chicken head mode on or off; return (whether it is as asked, what to tell).""" + if not enabled: + if self.head is not None: + self.end_head('Chicken head off: the arm holds where it is', hand_back=True) + return True, 'Chicken head is off' + if self.head is not None: + return True, 'Chicken head is already on' + problem = self.head_problem() + if problem: + return False, problem + self.stop_cartesian() + self.velocities = dict.fromkeys(self.limits, 0.0) + self.command_targets = dict(self.targets) + self.head = HeadMode(self.head_goal) + self.note, self.warning = 'Chicken head: moving the tip to the head position', False + return True, 'Chicken head is on: moving the tip to the head position' + + def end_head(self, note='', hand_back=False): + """ + Leave chicken head mode, if it is on, holding the arm where it is. + + With ``hand_back``, the sticks that tilt and roll the tool must be centred before the + active group's sticks move the arm. + """ + if self.head is None: + return + self.head = None + self.stop_cartesian() + self.velocities = dict.fromkeys(self.limits, 0.0) + self.command_targets = dict(self.targets) + if note: + self.note, self.warning = note, False + if hand_back: + self.hand_back() + + def head_step(self, axes, dt): + """Take one step of chicken head mode: toward the head spot, or holding it.""" + if self.head.anchor is None: + self.head_approach(dt) + else: + self.head_hold(axes, dt) + + def head_approach(self, dt): + """Move every arm joint in a straight line, in joint space, to the goal pose.""" + head, config = self.head, self.config + joints = self.kinematics.joints + error = {joint: head.goal[joint] - self.targets[joint] for joint in joints} + distance = max(abs(value) for value in error.values()) + if distance <= HEAD_ARRIVED: + self.targets.update(head.goal) + self.command_targets.update(head.goal) + for joint in joints: + self.velocities[joint] = 0.0 + head.anchor = self.kinematics.forward(head.goal)[0] + self.wait_for_center = True + self.wait_note = 'Center motion controls before tilting or rolling the head' + return + # Speed up at the acceleration limit and slow down so that every joint stops together. + head.rate = min(head.rate + config.max_accel * dt, self.speed, + math.sqrt(2.0 * config.max_accel * distance)) + step = min(head.rate * dt, distance) + remaining = distance - step + ahead = min(head.rate * config.period, remaining) + for joint in joints: + self.targets[joint] += error[joint] * step / distance + self.velocities[joint] = error[joint] * step / distance / dt + self.command_targets[joint] = self.targets[joint] + error[joint] * ahead / distance + + def nearest_limit(self): + """Name the arm joint closest to one of its limits, or 'reach' if none is close.""" + margins = {joint: min(self.targets[joint] - self.limits[joint][0], + self.limits[joint][1] - self.targets[joint]) + for joint in self.kinematics.joints} + joint = min(margins, key=margins.get) + return [joint] if margins[joint] < HEAD_NEAR_LIMIT else ['reach'] + + def head_hold(self, axes, dt): + """Tilt and roll the tool about the held tip, with the tip pulled back to the spot.""" + config, kinematics, head = self.config, self.kinematics, self.head + settings = config.head + if dt <= 0: + return + top = config.tilt_speed * config.speed_levels[self.level] + # Stick up tilts the tool up, which lowers the pitch angle, as the tilt buttons do. + tilt = clamp( + -settings.tilt_scale * self.stick(axes, settings.tilt_axis) * top + + top * ((config.buttons['tilt_down'] in self.held) + - (config.buttons['tilt_up'] in self.held)), -top, top) + roll = settings.roll_scale * self.stick(axes, settings.roll_axis) * self.speed + step = config.max_accel * dt + tilt = self.tilt + clamp(tilt - self.tilt, -step, step) + roll = self.roll + clamp(roll - self.roll, -step, step) + before = {joint: self.targets[joint] for joint in kinematics.joints} + tip, _ = kinematics.forward(before) + pull = [HEAD_PULL * (goal - now) / dt for goal, now in zip(head.anchor, tip)] + after, fraction, self.blocked = kinematics.jog( + before, pull, tilt, roll, dt, self.limits, config.max_speed) + if not self.blocked and fraction < HEAD_STALLED and (abs(tilt) > 1e-6 or abs(roll) > 1e-6): + self.blocked = self.nearest_limit() + self.tilt, self.roll = tilt * fraction, roll * fraction + for joint in kinematics.joints: + self.velocities[joint] = (after[joint] - before[joint]) / dt + self.targets[joint] = after[joint] + if self.tilt or self.roll: + future, _, _ = kinematics.jog( + after, (0.0, 0.0, 0.0), self.tilt, self.roll, config.period, self.limits, + config.max_speed) + else: + future = after + self.command_targets.update(future) + + def demo_status(self): + """Return demo mode's state, one of DEMO_STATES, and a line saying what is going on.""" + if self.demo_misfit: + return 'unavailable', DEMO_UNAVAILABLE + if self.demo is None: + return 'off', self.demo_ended + if self.demo.ramp.goal == 0.0: + return 'stopping', 'Returning to the pose it started from' + return 'running', 'Moving slowly around its start pose; B stops it at once' + + def demo_plan(self): + """Return ({joint: (amplitude, cycles, phase)}, '') for a swing that fits, or why not.""" + if self.demo_misfit: + return {}, DEMO_UNAVAILABLE + if not self.enabled: + return {}, 'Press Start (Xbox Menu button) first, then switch Demo mode on' + if self.head is not None: + return {}, 'Switch Chicken head off first' + if self.inserted(): + return {}, 'The tool is inserted; withdraw it to the incision point first' + demo, swings = self.config.demo, {} + for joint, amplitude, cycles, phase in zip( + demo.joints, demo.amplitudes, demo.cycles, demo.phases): + lower, upper = self.limits[joint] + room = min(self.targets[joint] - lower, upper - self.targets[joint]) - demo.margin + if self.movable(joint) and min(amplitude, room) >= demo.min_swing: + swings[joint] = (min(amplitude, room), cycles, phase) + if not swings: + if any(self.movable(joint) for joint in demo.joints): + return {}, ('No joint has room to swing here; move the arm away from its joint ' + 'limits first') + return {}, 'No demo joint can move: they are locked or switched off' + for scale in DEMO_SCALES: + scaled = {joint: (amplitude * scale, cycles, phase) + for joint, (amplitude, cycles, phase) in swings.items()} + hit = self.swing_hit(scaled) + if not hit: + return scaled, '' + return {}, (f'Swinging here would take the arm into {hit}; move it away from the table ' + 'and the base first') + + def swing_hit(self, swings): + """Name what the arm would touch at the extremes of the swings, or '' if nothing.""" + if self.collision is None: + return '' + joints = list(swings) + reach = {joint: swings[joint][0] for joint in joints} + # The start pose, each joint at either end of its swing, and every mix of the ends. + offsets = [{}] + offsets += [{joint: sign * reach[joint]} for joint in joints for sign in (-1.0, 1.0)] + offsets += [{joint: sign * reach[joint] for joint, sign in zip(joints, signs)} + for signs in itertools.product((-1.0, 1.0), repeat=len(joints))] + for offset in offsets: + pose = {joint: angle + offset.get(joint, 0.0) for joint, angle in self.targets.items()} + found = self.collision.check(pose) + if found: + return ', '.join(found) + return '' + + def demo_tempo(self): + """Return how fast the demo clock runs: 1 at the starting speed level, less below it.""" + levels = self.config.speed_levels + return min(1.0, levels[self.level] / levels[self.config.speed_level]) + + def set_demo_mode(self, enabled): + """Switch demo mode on or off; return (whether it is as asked, what to tell).""" + demo = self.demo + if not enabled: + if demo is None: + return True, 'Demo mode is off' + demo.ramp.aim(0.0) + self.note, self.warning = 'Demo mode off: returning to the pose it started from', False + return True, 'Demo mode is stopping: the arm is returning to the pose it started from' + if demo is not None: + demo.ramp.aim(1.0) + self.note, self.warning = 'Demo mode: moving slowly around its start pose', False + return True, 'Demo mode is on' + swings, problem = self.demo_plan() + if problem: + return False, problem + self.stop_cartesian() + self.velocities = dict.fromkeys(self.limits, 0.0) + self.command_targets = dict(self.targets) + settings = self.config.demo + self.demo = Wander({joint: self.targets[joint] for joint in swings}, swings, + settings.loop, settings.ramp, self.demo_tempo()) + self.demo_ended = '' + self.note, self.warning = 'Demo mode: moving slowly around its start pose', False + return True, 'Demo mode is on: the arm is starting to move slowly' + + def end_demo(self, note='', warning=False, hand_back=False): + """Leave demo mode, if it is on, holding the arm where it is.""" + if self.demo is None: + return + self.demo = None + self.demo_ended = note if warning else '' + self.stop_cartesian() + self.velocities = dict.fromkeys(self.limits, 0.0) + self.command_targets = dict(self.targets) + if note: + self.note, self.warning = note, warning + if hand_back: + self.hand_back() + + def demo_step(self, dt): + """Advance the demo and return the joint velocities that follow its swing.""" + if dt <= 0: + return {} + self.demo.advance(dt, self.demo_tempo()) + cap = self.config.demo.max_speed + return {joint: clamp((goal - self.targets[joint]) / dt, -cap, cap) + for joint, goal in self.demo.positions().items()} + + def demo_settle(self): + """End the demo if a step ran into something, or once its swing has shrunk to nothing.""" + stopped = [name for name in self.blocked if name != self.config.tool_joint] + if stopped: + self.end_demo('Demo stopped: blocked by ' + ', '.join(stopped), + warning=True, hand_back=True) + elif self.demo.finished: + # Back at the start pose, less the rounding of every step it took. + self.targets.update(self.demo.centre) + self.end_demo('Demo mode finished: the arm is back where it started', + hand_back=True) + def incise(self, axes, dt): """ Slide the tool along its own axis, or tilt it about the incision point. diff --git a/waybionic_teleop/waybionic_teleop/wander.py b/waybionic_teleop/waybionic_teleop/wander.py new file mode 100644 index 0000000..50e5172 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/wander.py @@ -0,0 +1,123 @@ +""" +Slow, smooth wandering of the arm's joints, for demo mode (pure logic, no ROS). + +Each joint swings sinusoidally about the pose the arm was in when the demo began, at its own +rate, so the arm moves around without repeating itself for a whole loop. The swing grows from +nothing when the demo starts and shrinks back to nothing when it stops, so the arm leaves its +pose gently and returns to exactly that pose. Everything runs on a demo clock that the speed +level can slow down, so slowing the demo slows the start and the return as well. +""" + +import math + +# How fast the demo clock may speed up or slow down, per second, so that changing the speed +# level never jerks the arm. +TEMPO_RATE = 0.25 +# The most a ramp changes per ramp duration: 1.875 from rest, and up to 2.3 when it is reversed +# part-way. A joint's speed is at most its swing's own plus this share of its size. +RAMP_PEAK = 2.5 +# The least share of the way a ramp plans for, so that a goal given before it has moved at all +# is reached in a moment rather than never. +MIN_TRIP = 1e-4 + + +def clamp(value, low, high): + return min(max(value, low), high) + + +class Ramp: + """ + A level that glides between 0 and 1 in ``duration`` seconds. + + It follows a quintic, minimum-jerk path, so its value, rate and acceleration change + smoothly. A new goal given part-way takes over from the current level, rate and + acceleration, so reversing never makes a jump in any of them. A trip of only part of the + way takes the square root of that part of the duration, which is as gentle as the whole + trip, whatever its length. + """ + + def __init__(self, duration, level=0.0): + if not 0 < duration < math.inf: + raise ValueError('a ramp needs a positive, finite duration') + self.duration = float(duration) + self.level, self.rate, self.accel = float(level), 0.0, 0.0 + self.goal = self.level + # How long the current trip takes, and how far along it is. + self.span = self.elapsed = self.duration + self.coefficients = (self.level, 0.0, 0.0, 0.0, 0.0, 0.0) + + @property + def settled(self): + return self.elapsed >= self.span + + def aim(self, goal): + """Head for ``goal`` from wherever the level, its rate and its acceleration are now.""" + if goal == self.goal: + return + self.goal = float(goal) + x0, v0, a0 = self.level, self.rate, self.accel + change = self.goal - x0 + span = self.span = self.duration * math.sqrt(max(abs(change), MIN_TRIP)) + self.coefficients = ( + x0, v0, a0 / 2.0, + (20.0 * change - 12.0 * v0 * span - 3.0 * a0 * span ** 2) / (2.0 * span ** 3), + (-30.0 * change + 16.0 * v0 * span + 3.0 * a0 * span ** 2) / (2.0 * span ** 4), + (12.0 * change - 6.0 * v0 * span - a0 * span ** 2) / (2.0 * span ** 5)) + self.elapsed = 0.0 + + def step(self, dt): + """Move ``dt`` seconds along the path and return the level.""" + if self.settled: + return self.level + self.elapsed = min(self.elapsed + dt, self.span) + if self.settled: + self.level, self.rate, self.accel = self.goal, 0.0, 0.0 + return self.level + t = self.elapsed + c0, c1, c2, c3, c4, c5 = self.coefficients + level = c0 + t * (c1 + t * (c2 + t * (c3 + t * (c4 + t * c5)))) + self.rate = c1 + t * (2.0 * c2 + t * (3.0 * c3 + t * (4.0 * c4 + t * 5.0 * c5))) + self.accel = 2.0 * c2 + t * (6.0 * c3 + t * (12.0 * c4 + t * 20.0 * c5)) + # A reversal can overshoot a hair; the swing never goes beyond its size or below nothing. + self.level = clamp(level, 0.0, 1.0) + return self.level + + +class Wander: + """ + The joints' swing about a centre pose, on a demo clock. + + ``swings`` is {joint: (amplitude rad, cycles, phase rad)}: the joint makes ``cycles`` whole + swings per ``loop`` seconds, so the whole motion repeats exactly every ``loop`` seconds of + demo time once it has grown to full size. + """ + + def __init__(self, centre, swings, loop, ramp, tempo=1.0): + if not 0 < loop < math.inf: + raise ValueError('the loop must take a positive, finite time') + self.centre = dict(centre) + self.swings = {joint: (amplitude, 2.0 * math.pi * cycles / loop, phase) + for joint, (amplitude, cycles, phase) in swings.items()} + self.ramp = Ramp(ramp) + self.ramp.aim(1.0) + self.clock = 0.0 + self.tempo = tempo + + @property + def finished(self): + """Whether the swing has shrunk to nothing, so the arm is back at the centre pose.""" + return self.ramp.goal == 0.0 and self.ramp.settled + + def advance(self, dt, tempo): + """Move ``dt`` seconds on, with the demo clock heading for ``tempo`` times real time.""" + self.tempo += clamp(tempo - self.tempo, -TEMPO_RATE * dt, TEMPO_RATE * dt) + gone = self.tempo * dt + self.clock += gone + self.ramp.step(gone) + + def positions(self): + """Return {joint: angle} at the demo clock.""" + size = self.ramp.level + return {joint: self.centre[joint] + + size * amplitude * math.sin(omega * self.clock + phase) + for joint, (amplitude, omega, phase) in self.swings.items()} diff --git a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py index afb1b42..1f08d29 100644 --- a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py +++ b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py @@ -5,7 +5,10 @@ a joint the arm profile (``arm_profile``) locks stays at its angle, and so does one the drive node reports switched off on ``arm/joint_control``. The logic lives in :mod:`waybionic_teleop.teleop`. The node also reports its state on /diagnostics and draws a -placeholder end effector and a status label in RViz. +placeholder end effector and a status label in RViz. Chicken head mode, which holds the tool +tip at a spot while the sticks tilt and roll the tool, and demo mode, which moves the arm around +slowly by itself, are each switched with a service and reported on a latched topic +(:mod:`waybionic_teleop.chicken_head`, :mod:`waybionic_teleop.demo_mode`). """ import math @@ -18,9 +21,10 @@ from rclpy.qos import DurabilityPolicy, QoSProfile from sensor_msgs.msg import JointState, Joy, JoyFeedback from std_msgs.msg import Bool, String +from std_srvs.srv import SetBool from visualization_msgs.msg import Marker, MarkerArray -from waybionic_teleop import joint_control +from waybionic_teleop import chicken_head, demo_mode, joint_control from waybionic_teleop.arm_profile import load_profile from waybionic_teleop.collision import ArmCollision from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS @@ -88,6 +92,10 @@ def __init__(self, **kwargs): self.create_subscription(JointState, 'joint_states', self.on_joint_states, 10) self.create_subscription(DiagnosticArray, joint_control.TOPIC, self.on_joint_control, latched) + self.head_publisher = self.create_publisher(DiagnosticArray, chicken_head.TOPIC, latched) + self.create_service(SetBool, chicken_head.SERVICE, self.on_head) + self.demo_publisher = self.create_publisher(DiagnosticArray, demo_mode.TOPIC, latched) + self.create_service(SetBool, demo_mode.SERVICE, self.on_demo) self.command_publisher = self.create_publisher(JointState, 'joint_commands', 10) self.enable_publisher = self.create_publisher(Bool, 'teleop_enabled', latched) # game_controller_node rumbles a local controller; joy_udp_receiver passes it on. @@ -160,6 +168,36 @@ def on_joy(self, message): self.joy, self.joy_time = message, time.monotonic() self.joy_count += 1 + def on_head(self, request, response): + if self.teleop is None: + response.success, response.message = False, self.problem + else: + response.success, response.message = self.teleop.set_head_mode(request.data) + self.publish_head() + return response + + def publish_head(self): + if self.teleop is None: + state, message = chicken_head.UNAVAILABLE, self.problem + else: + state, message = self.teleop.head_status() + self.head_publisher.publish(chicken_head.head_message(state, message)) + + def on_demo(self, request, response): + if self.teleop is None: + response.success, response.message = False, self.problem + else: + response.success, response.message = self.teleop.set_demo_mode(request.data) + self.publish_demo() + return response + + def publish_demo(self): + if self.teleop is None: + state, message = demo_mode.UNAVAILABLE, self.problem + else: + state, message = self.teleop.demo_status() + self.demo_publisher.publish(demo_mode.demo_message(state, message)) + def on_joint_control(self, message): self.disabled = joint_control.disabled_joints(message) self.apply_disabled() @@ -275,7 +313,9 @@ def summary(self, fresh): state += '\n' + stop_reason(teleop.blocked) else: state = 'DISABLED\nPRESS-MENU' if fresh else 'NO-CONTROLLER' - return f'{teleop.active_group.name.upper()}\n{self.speed_percent():.0f}%\n{state}' + name = ('HEAD' if teleop.head is not None else 'DEMO' if teleop.demo is not None + else teleop.active_group.name.upper()) + return f'{name}\n{self.speed_percent():.0f}%\n{state}' def speed_percent(self): return 100.0 * self.config.speed_levels[self.teleop.level] @@ -335,31 +375,46 @@ def report(self): else: group = teleop.active_group cartesian = group.mode == 'cartesian' + head, demo = teleop.head is not None, teleop.demo is not None hint = 'B stops, Y switches group, A holds to go home' - if group.mode == 'incision': + if head: + hint = 'B stops; Y or A leaves chicken head' + elif demo: + hint = 'B stops; Y or A leaves demo mode' + elif group.mode == 'incision': hint = ('Tilt stays in the arm plane; going home is off here; B stops; ' 'Y switches once the tool is withdrawn') note = teleop.note or ('At limit: ' + ', '.join(teleop.blocked) if teleop.blocked else ('LB moves along one axis; ' if cartesian else '') + hint) if teleop.disabled: note = f'Joints off: {", ".join(sorted(teleop.disabled))}; {note}' - speed = (f'{1000.0 * teleop.linear_speed:.1f} mm/s' if group.mode != 'joint' + speed = (f'{1000.0 * teleop.linear_speed:.1f} mm/s' + if group.mode != 'joint' and not (head or demo) else f'{math.degrees(teleop.speed):.0f} deg/s') + speed_note = f'{speed} max; D-pad up/down changes it' + if demo: + top = math.degrees(min(teleop.speed, self.config.demo.max_speed)) + speed_note = f'{top:.0f} deg/s max; D-pad down slows it, up does not speed it up' low, high = self.config.tool_limits closed = (self.measured.get(self.config.tool_joint, low) - low) / (high - low) statuses += [ status('teleop.state', DiagnosticStatus.WARN if teleop.warning else DiagnosticStatus.OK, 'enabled' if teleop.enabled else 'disabled', '', note), - status('teleop.group', DiagnosticStatus.OK, group.name, '', group.describe()), + status('teleop.group', DiagnosticStatus.OK, + 'chicken head' if head else 'demo' if demo else group.name, '', + teleop.head_status()[1] if head else teleop.demo_status()[1] if demo + else group.describe()), status('teleop.speed', DiagnosticStatus.OK, f'{self.speed_percent():.0f}', '%', - f'{speed} max; D-pad up/down changes it'), + speed_note), status('teleop.tool', DiagnosticStatus.OK, f'{100.0 * closed:.0f}', '%', 'closed (placeholder end effector); RT closes, LT opens'), ] message = DiagnosticArray(status=statuses) message.header.stamp = self.get_clock().now().to_msg() self.diagnostics_publisher.publish(message) + self.publish_head() + self.publish_demo() def main():