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.wpilibj.smartdashboard; 006 007import edu.wpi.first.networktables.DoublePublisher; 008import edu.wpi.first.networktables.NetworkTable; 009 010/** 011 * Root Mechanism2d node. 012 * 013 * <p>A root is the anchor point of other nodes (such as ligaments). 014 * 015 * <p>Do not create objects of this class directly! Obtain instances from the {@link 016 * Mechanism2d#getRoot(String, double, double)} factory method. 017 * 018 * <p>Append other nodes by using {@link #append(MechanismObject2d)}. 019 */ 020public final class MechanismRoot2d extends MechanismObject2d { 021 private double m_x; 022 private DoublePublisher m_xPub; 023 private double m_y; 024 private DoublePublisher m_yPub; 025 026 /** 027 * Package-private constructor for roots. 028 * 029 * @param name name 030 * @param x x coordinate of root (provide only when constructing a root node) 031 * @param y y coordinate of root (provide only when constructing a root node) 032 */ 033 MechanismRoot2d(String name, double x, double y) { 034 super(name); 035 m_x = x; 036 m_y = y; 037 } 038 039 @Override 040 public void close() { 041 if (m_xPub != null) { 042 m_xPub.close(); 043 } 044 if (m_yPub != null) { 045 m_yPub.close(); 046 } 047 super.close(); 048 } 049 050 /** 051 * Set the root's position. 052 * 053 * @param x new x coordinate 054 * @param y new y coordinate 055 */ 056 public synchronized void setPosition(double x, double y) { 057 m_x = x; 058 m_y = y; 059 flush(); 060 } 061 062 @Override 063 protected synchronized void updateEntries(NetworkTable table) { 064 if (m_xPub != null) { 065 m_xPub.close(); 066 } 067 m_xPub = table.getDoubleTopic("x").publish(); 068 if (m_yPub != null) { 069 m_yPub.close(); 070 } 071 m_yPub = table.getDoubleTopic("y").publish(); 072 flush(); 073 } 074 075 private void flush() { 076 if (m_xPub != null) { 077 m_xPub.set(m_x); 078 } 079 if (m_yPub != null) { 080 m_yPub.set(m_y); 081 } 082 } 083}