Reading Array Values Published by NetworkTables

This article describes how to read values published by NetworkTables using a program running on the robot. This is useful when using computer vision where the images are processed on your driver station laptop and the results stored into NetworkTables possibly using a separate vision processor like a raspberry pi, or a tool on the robot like a python program to do the image processing.

Comúnmente los valores son para una o más áreas de interés tales como objetivos o piezas de juego y son regresadas múltiples instancias. En el ejemplo a continuación, varios valores x, y, ancho, altura, y áreas son entregados por el procesamiento de imagen y el programa del robot puede decidir cuál de los valores entregados son de interés para los siguientes procesamientos.

Verify the NetworkTables Topics Being Published

Image of OutlineViewer with the NetworkTables topics

You can verify the names of the NetworkTables topics used for publishing the values by using the Outline Viewer application. It is a C++ program in your user directory in the wpilib/<YEAR>/tools folder. The application is started by selecting the «WPILib» menu in Visual Studio Code then Start Tool then «OutlineViewer». In this example, with the image processing program running (GRIP) you can see the values being put into NetworkTables.

In this case the values are stored in a table called GRIP and a sub-table called myContoursReport. You can see that the values are in brackets and there are 2 values in this case for each topic. The NetworkTables topic names are centerX, centerY, area, height and width.

Los dos ejemplos siguientes son programas extremadamente simplificados que solamente ilustran el uso de las Tablas de Enrutamiento. Todo el código se encuentra en el método robotInit() que solo se ejecuta cuando el programa inicia. En sus programas, usted buscará obtener los valores del código que evalúen en que dirección apuntar el robot en un comando o un bucle de control durante los periodos de autónomo o teleoperado.

Writing a Program to Access the Topics

DoubleArraySubscriber areasSub;

@Override
public void robotInit() {
  NetworkTable table = NetworkTableInstance.getDefault().getTable("GRIP/mycontoursReport");
  areasSub = table.getDoubleArrayTopic("area").subscribe(new double[] {});
}

@Override
public void teleopPeriodic() {
    double[] areas = areasSub.get();

    System.out.print("areas: " );

    for (double area : areas) {
      System.out.print(area + " ");
    }

    System.out.println();
}
nt::DoubleArraySubscriber areasSub;

void Robot::RobotInit() override {
  auto table = nt::NetworkTableInstance::GetDefault().GetTable("GRIP/myContoursReport");
  areasSub = table->GetDoubleArrayTopic("area").Subscribe({});
}

void Robot::TeleopPeriodic() override {
  std::cout << "Areas: ";

  std::vector<double> arr = areasSub.Get();

  for (double val : arr) {
    std::cout << val << " ";
  }

  std::cout << std::endl;
}
def robotInit(self):
    table = ntcore.NetworkTableInstance.getDefault().getTable("GRIP/mycontoursReport")
    self.areasSub = table.getDoubleArrayTopic("area").subscribe([])

def teleopPeriodic(self):
    areas = self.areasSub.get()
    print("Areas:", areas)

Los pasos para obtener los valores y, en este programa, escribirlos son:

  1. Declarar la tabla variable que guardará la instancia de la subtabla que tendrá los valores.

  2. Inicializar la instancia de la subtabla para que pueda ser usada después para recuperar los valores.

  3. Read the array of values from NetworkTables. In the case of a communicating programs, it’s possible that the program producing the output being read here might not yet be available when the robot program starts up. To avoid issues of the data not being ready, a default array of values is supplied. This default value will be returned if the NetworkTables topic hasn’t yet been published. This code will loop over the value of areas every 20ms.

Program Output

Image of Riolog showing the values

En este caso el programa solamente está buscando en la matriz de las areas, pero en un ejemplo real sería más probable usar todos los valores. Usando el Riolog en VS Code o la Driver Station Log puede ver los valores así como son enviados. Este programa está usando de muestra una imagen estática así que las areas no cambian, pero puede imaginar que con la cámara en el robot, los valores estarían constantemente cambiando.