001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.wpilibj2.command;
006
007import edu.wpi.first.util.sendable.Sendable;
008import edu.wpi.first.util.sendable.SendableBuilder;
009import edu.wpi.first.util.sendable.SendableRegistry;
010
011/**
012 * A base for subsystems that handles registration in the constructor, and provides a more intuitive
013 * method for setting the default command.
014 */
015public abstract class SubsystemBase implements Subsystem, Sendable {
016  /** Constructor. */
017  public SubsystemBase() {
018    String name = this.getClass().getSimpleName();
019    name = name.substring(name.lastIndexOf('.') + 1);
020    SendableRegistry.addLW(this, name, name);
021    CommandScheduler.getInstance().registerSubsystem(this);
022  }
023
024  /**
025   * Gets the name of this Subsystem.
026   *
027   * @return Name
028   */
029  public String getName() {
030    return SendableRegistry.getName(this);
031  }
032
033  /**
034   * Sets the name of this Subsystem.
035   *
036   * @param name name
037   */
038  public void setName(String name) {
039    SendableRegistry.setName(this, name);
040  }
041
042  /**
043   * Gets the subsystem name of this Subsystem.
044   *
045   * @return Subsystem name
046   */
047  public String getSubsystem() {
048    return SendableRegistry.getSubsystem(this);
049  }
050
051  /**
052   * Sets the subsystem name of this Subsystem.
053   *
054   * @param subsystem subsystem name
055   */
056  public void setSubsystem(String subsystem) {
057    SendableRegistry.setSubsystem(this, subsystem);
058  }
059
060  /**
061   * Associates a {@link Sendable} with this Subsystem. Also update the child's name.
062   *
063   * @param name name to give child
064   * @param child sendable
065   */
066  public void addChild(String name, Sendable child) {
067    SendableRegistry.addLW(child, getSubsystem(), name);
068  }
069
070  @Override
071  public void initSendable(SendableBuilder builder) {
072    builder.setSmartDashboardType("Subsystem");
073
074    builder.addBooleanProperty(".hasDefault", () -> getDefaultCommand() != null, null);
075    builder.addStringProperty(
076        ".default",
077        () -> getDefaultCommand() != null ? getDefaultCommand().getName() : "none",
078        null);
079    builder.addBooleanProperty(".hasCommand", () -> getCurrentCommand() != null, null);
080    builder.addStringProperty(
081        ".command",
082        () -> getCurrentCommand() != null ? getCurrentCommand().getName() : "none",
083        null);
084  }
085}