Hello World 2

1. Introduction

In the previous tutorial, you worked with the MessagePrinter Component Type, and learned how to configure it to print a message you chose at build time. This helped you understand the various stages involved in building ground software with Groundkit, but was not a very realistic development task.

Typically, when using Groundkit to produce your ground software you will need to create or modify Component Types and write their implementations.

In this tutorial you will learn how to do that. You will add new functionality to the MessagePrinter Component Type, implement it, and then test it in a Deployment Type.

Along the way, you will learn how to create Actions which take Arguments. You will also be introduced to Parameters, which are used to give access to, and control over, a Component Instance's State.

In this tutorial, you will:

  • Get more comfortable with the workflow involved in writing Component Implementations.

  • Learn how to create Actions which take Arguments.

  • Learn about Parameters, and how they can be implemented by adding to the Component Type Structure.

  • Learn how to use Locks to protect resources from multiple access.

2. Before You Begin

Guidance on the styles and conventions used in these tutorials is available here.

Unless otherwise directed, all commands in this tutorial must be run in the the_basics/HelloWorld2 workspace.

You must have Groundkit installed as described in the Getting Started Guide.

Install a copy of the tutorials locally by running hgk-prepare-tutorials.

Navigate to the the_basics/HelloWorld2 workspace in a terminal and run hgk workspace prepare to ensure it is ready to use.

3. Actions With Arguments

In the previous tutorial, you were briefly introduced to Actions as a way to execute a Component Instance's functionality on command.

Actions can also have an Argument. Like the arguments of a method in Java, an Action's Argument can be used to dynamically control its behaviour.

In this section of the tutorial you will add a new printUserMessage Action. Rather than printing a message defined in the MessagePrinter initialisation data, this Action will print the message you provide as an Argument.

3.1. Adding the printUserMessage Action

To add a new Action to a Component Type, you need to add a new <Action> element to its componentType.xml. To specify that an Action takes an Argument, you also need to include an <Argument> element.

Open the MessagePrinter componentType.xml, found here:

library/componenttypes/messageprinter/src/main/resources/com/brightascension/componenttypes/messageprinter/componentType.xml

Add the following <Action> element below the printGreeting Action:

<Action name="printUserMessage">
  <Description>
    Print a message, provided as an argument, to the console.
  </Description>
  <Argument name="message">
    <Description>
      The message to print.
    </Description>
    <Type>
      <Blob fixed="false" maxLength="127"/>
    </Type>
  </Argument>
</Action>

Having changed the componentType.xml, you now need to generate the Component Type.

hgk component-type generate MessagePrinter

Since an implementation file already exists for the MessagePrinter Component Type, the above command creates a template file. This file contains skeleton code for the Component Type's updated implementation and can be used to update the original file. The template file is named MessagePrinterImpl.java.template and can be found here:

library/componenttypes/messageprinter/src/main/java/com/brightascension/componentimpls/messageprinter/messageprinterimpl/MessagePrinterImpl.java.template

To update the original implementation file, you can simply copy over the new methods that are needed from the generated template file. It is recommended that you retain the same method order in the original file as is in the template file to help with comparisons and maintenance.

Copy the skeleton code for MessagePrinterImpl.printUserMessage(byte[] message) from MessagePrinter.java.template (including its description banner) and paste it below the MessagePrinterImpl.printGreeting() method in MessagePrinterImpl.java.

Notice that, unlike the MessagePrinter_printGreeting() method, the new Action function has a byte[] message argument. The maximum length of this byte array is enforced by some generated template code against limits derived from the model. These limits can be found in library/componenttypes/messageprinter/src/main/java/com/brightascension/componentimpls/messageprinter/messageprinterimpl/include/container/component/aas/MessagePrinterImplActions.java with the length checking implemented in library/componenttypes/messageprinter/generated/main/java/com/brightascension/componentimpls/messageprinter/messageprinterimpl/component/aas/MessagePrinterImplActionSource.java.

In this case, the generated code is validating that message.length does not exceed the maximum length of the message Argument specified in the XML excerpt you just added.

Many different methods and static fields are generated from the data entered into the model for a Component Type.

We demonstrate some of these static fields in these tutorials. In future we are planning to provide more complete documentation of all the generated methods and static fields which your Component Types can use.

You must now update the implementation so it prints out the byte array message.

You can try this yourself if you wish, or if you’d prefer you can use the implementation we’ve provided below.

Show the modifications to the MessagePrinterImpl.printUserMessage() Action skeleton
 import com.brightascension.componentimpls.messageprinter.messageprinterimpl.include.container.MessagePrinterImplContainer;
 import com.brightascension.componentimpls.messageprinter.messageprinterimpl.include.container.MessagePrinterImplInterface;
 import com.brightascension.genone.exception.GenOneBaseException;
+import com.brightascension.genone.util.SerialisationUtils;

 /**
  * This is the Component Implementation for MessagePrinter.
@@ -65,6 +66,18 @@ public class MessagePrinterImpl implements MessagePrinterImplInterface {
     container.logInfo("Greeting says '{}'", greeting);
   }

+  /**
+   * The printUserMessage action from the Component Type : MessagePrinter
+   * Print a message, provided as an argument, to the console.
+   * @param message The message to print.
+   * @throws GenOneBaseException
+   */
+  public void printUserMessage(byte[] message) throws GenOneBaseException {
+    String messageStr = SerialisationUtils.deserialiseFixedString(message);
+    container.logInfo("Printing message '{}'", messageStr);
+  }
+
   @Override
   public String toString() {
     return String.format("%s - %d", instanceName, id);

The MessagePrinter Component Type now has a new Action printUserMessage.

3.2. Testing the printUserMessage Action

Like in the HelloWorld1 tutorial, MessagePrinter has already been instantiated for you in a Deployment Type, and that Deployment Type has been instantiated in a Mission.

In order to invoke the printUserMessage Action, you must build the HelloWorld2 Mission, and run the MessagePrinterDemo Deployment Instance.

Use the same commands as in the previous tutorial to build the Mission and run the Deployment Instance:

hgk mission build HelloWorld2
java -jar output/missions/HelloWorld2/MessagePrinterDemo/MessagePrinterDeployment/MessagePrinterDeployment.jar

The Deployment Instance should start successfully:

15:50:13.547 [main] INFO  c.b.m.h.m.m.deployment.Deployment - Initialising the MessagePrinterDeployment Deployment.
15:50:13.602 [GRPCServerInst-serverStartup-thread-0] INFO  c.b.c.g.g.g.GRPCServerImpl - Starting server on port: 8900

With the Deployment Instance running, you can now interact with it using Helix Lab by sending TCP requests or Bruno with gRPC requests.

3.2.1. Using Lab

Use the same approach as in the previous tutorial to load the MDB and connect to the running Deployment Instance:

  • Launch Lab from the application menu.

  • Load the MDB (located here: output/missions/HelloWorld2/HelloWorld2_0_0_0.missiondb) using the Import .missiondb button on the 'Config' page.

  • Connect to the Deployment Instance by selecting the Connect button on the Command page and entering the hostname - their values should be localhost and 65534 respectively.

Once connected, use the Mission tree-view to find the printUserMessage Action associated with the MyMessagePrinter Component Instance in your Deployment Instance.

Click on the printUserMessage Action to add a command card representing that Action to the 'My Commands' section of the view.

Click on the printUserMessage command card in the 'My Commands' section to expand its layout.

The expanded command card contains a field for entering the Argument. The details of the Action's Argument were captured in the MDB and loaded by Lab. Lab automatically provides the user interface necessary to provide the new Argument data.

You can use this field to specify the message you want the Component Instance to print to the terminal, when this Action is invoked.

Notice that there is an 'H' indicator at the right side of the field. This specifies that the argument must be entered in hexadecimal format.

helix lab command card h input

Type the string that you want to be printed to the terminal, in hexadecimal format, into the Argument field, then click Invoke.

String to hex converters which are readily available online can be used to help with this step.

Show example argument

To print the word HelloWorld2, input its hexadecimal equivalent which is 48656c6c6f576f726c6432.

If successful, the terminal running your MessagePrinterDeployment Deployment Instance should now display your message:

15:58:07.975 [TCPServerInst-serverStartup-thread-0] INFO  c.b.c.m.m.MessagePrinterImpl - Printing message 'HelloWorld2'

Once you are happy the Action is working, disconnect Lab from the Deployment Instance.

If you wish to test with Bruno as well, leave the Deployment Instance running and continue with the steps in the next section. Otherwise, terminate the instance before proceeding.

Keep Lab open so you can use it again later in the tutorial.

In this section you added an Action which takes an Argument - printUserMessage - to the MessagePrinter Component Type. You have implemented this Action such that it prints its Argument.

In the next section you will be introduced to Parameters. You will create one which interacts with the printUserMessage Action to give insight into the behaviour of MessagePrinter Component Instances at runtime.

3.2.2. Using Bruno

Use the same approach as in the previous tutorial to open Bruno and load the collection provided at bruno/HelloWorld2:

  • Launch Bruno from the application menu.

  • Click the Open Collection button and navigate to the collection and click the Open button.

  • Select the invoke_action_print_user_data request under the HelloWorld2 collection.

{
  "provider_id": {
    "target_id": 0,
    "deployment_id": 0,
    "local_provider_id": 0
  },
  "channel_id": 0,
  "selection_id": 1,
  "args_in": "SGVsbG9Xb3JsZDI="
}

Notice that the selection_id is set to 1 in contrast to the invoke_action_print_greeting request. This is because the actions are indexed in the order they are defined in the componentType.xml file.

The request JSON contains an args_in JSON property for entering the printUserGreeting Argument. You can use this property to specify the message you want the Component Instance to print to the terminal, when this Action is invoked. The value should be encoded in base64.

Replace the args_in value with the string that you want to be printed to the terminal, in base64 encoding.

The Linux command line base64 utility can be used to do this encoding.

printf "Your string here" | base64
Show example argument

To print the word HelloWorld2, update args_in with its base64 equivalent which is SGVsbG9Xb3JsZDI=.

Click the → right arrow button at the top of the request to invoke the Action.

If successful, the terminal running your MessagePrinterDemo Deployment Instance should now display your message:

16:16:25.919 [grpc-default-executor-5] INFO  c.b.c.m.m.MessagePrinterImpl - Printing message 'HelloWorld2'

Once you are happy the Action is working, terminate the process using the same approach as in the previous tutorial.

Keep Bruno open so you can use it again later in the tutorial.

In this section you added an Action which takes an Argument - printUserMessage - to the MessagePrinter Component Type. You have implemented this Action such that it prints its Argument.

In the next section you will be introduced to Parameters. You will create one which interacts with the printUserMessage Action to give insight into the behaviour of MessagePrinter Component Instances at runtime.

4. Parameters

Parameters are one of the most widely used features of Component Types created with Groundkit. Almost every Component Type has at least one Parameter to give insight into, or control over, its behaviour:

  • Many Component Types have an enabled Parameter to allow them to be switched on and off.

  • Component Types which handle data transmission and reception may have Parameters for counting the number of bytes transmitted and received.

  • A Component Type for handling CFDP transmission might use Parameters to control the keep alive interval, and other settings.

Like variables in typed programming languages, Parameters have types. Parameters may be integers, floats, bitfields (not currently supported), raw byte blobs. They may also be lists of integers, floats or raw byte blobs.

Parameters are either mutable or read-only. The value of Mutable Parameters can be set externally to the Component Type, whereas the value of Read-Only Parameters can only be set internally by the Component Implementation.

In this section of the tutorial, you will add a Read-Only Parameter indicating how many times the printUserMessage Action has been invoked.

This will require the addition of a new Parameter to the Component Type, the addition of a new State variable to the Component Type Structure, and modification of the printUserMessage Action.

4.1. Adding the actionCounter Parameter

To add a new Parameter to a Component Type, you need to add a new <Parameter> element to its componentType.xml. MessagePrinter currently has no Parameters, so a <Parameters> element is also required.

Open the MessagePrinter componentType.xml and add the following <Parameters> element just below the <!-- Parameters --> comment:

<Parameters>
  <Parameter name="actionCounter" readOnly="true">
    <Description>
      The number of times the action has been invoked.
    </Description>
    <Type>
      <Integer signed="false" bits="32"/>
    </Type>
  </Parameter>
</Parameters>

As before, this changes the Component Type, so you must generate MessagePrinter:

hgk component-type generate MessagePrinter

The above command overwrites the template file MessagePrinterImpl.java.template with updated code including a new Parameter getter function, MessagePrinter.getActionCounter().

Copy this function, including its description banner, and paste it in MessagePrinterImpl.java just below the MessagePrinterImpl.printUserMessage() function.

You will now update the MessagePrinterImpl to record the number of times MessagePrinterImpl.printUserMessage() has been accessed, and implement the getter function.

4.2. Adding State to MessagePrinter

You need each instance of MessagePrinter to have its own counter, so a new field is required.

It is good practice to ensure the new member’s name and type match those defined for the Parameter in the componentType.xml. This makes your Component Implementation easier to understand for others. Note that since Java does not have unsigned integers, we use a long to represent this type. Appropriate size checking is provided in the generated code, and we will look at this later. It is also good practice to use Atomic* classes to provide thread-safe access to this member.

Open MessagePrinterImpl.java and add a new AtomicLong actionCounter field.

Show the added MessagePrinterImpl field
@@ -7,6 +7,9 @@ package com.brightascension.componentimpls.messageprinter.messageprinterimpl;
 import com.brightascension.componentimpls.messageprinter.messageprinterimpl.include.container.MessagePrinterImplContainer;
 import com.brightascension.componentimpls.messageprinter.messageprinterimpl.include.container.MessagePrinterImplInterface;
 import com.brightascension.genone.exception.GenOneBaseException;
 import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicLong;

 /**
  * This is the Component Implementation for MessagePrinter.
@@ -24,6 +27,8 @@ public class MessagePrinterImpl implements MessagePrinterImplInterface {
   // Container reference
   private final MessagePrinterImplContainer container;

+  private AtomicLong actionCounter = new AtomicLong();
+
   /**
    * Constructor for MessagePrinter
    *

4.3. Thread safety

Note that you need to access MessagePrinterImpl.actionCounter in 2 separate contexts:

  • MessagePrinterImpl.getActionCounter() to return its value to the user.

  • MessagePrinterImpl.printUserMessage() to increment it.

In general, there is nothing to stop the actionCounter Parameter and printUserMessage Action from being accessed concurrently. For example, the Action could be scheduled for autonomous invocation at the same time as a user happens to request the Parameter's value.

To prevent potentially dangerous race conditions, Component Implementations must use Locks to protect resources which may be accessed from different contexts. In most cases, we recommend using java.util.concurrent.atomic.* types. In this case, we have used an AtomicLong.

Practically, the chance of race conditions in this case is extremely small, but not negligible!

While the protected resource in this tutorial is very simple (a single 32-bit word), there are many situations, like the handling of packets in communications Component Types, where a failure to correctly protect underlying resources can cause very difficult to diagnose issues when the software is integrated.

4.4. Implementing the actionCounter Parameter

You now have all the elements needed to update the implementation such that actionCounter behaves as specified in the componentType.xml:

  • An underlying atomic State variable held in the MessagePrinterImpl.actionCounter field.

You will now update the implementation using these elements.

First, modify the MessagePrinterImpl.getActionCounter() Parameter getter function you added earlier so it returns the current value of MessagePrinterImpl.actionCounter to the user, accessing it from within the AtomicLong.

Show the updated MessagePrinterImpl.getActionCounter() implementation
@@ -88,8 +91,7 @@ public class MessagePrinterImpl implements MessagePrinterImplInterface {
    */
   @Override
   public long getActionCounter() throws GenOneBaseException {
-    // TODO: Implement actionCounter get accessor
-    throw new OperationNotProvidedException();
+    return actionCounter.get();
   }

   @Override

Next, update the MessagePrinterImpl.printUserMessage() method so that, each time the Action is invoked, it increments the actionCounter State variable.

Show the change required in the MessagePrinterImpl.printUserMessage() implementation
@@ -73,6 +76,7 @@ public class MessagePrinterImpl implements MessagePrinterImplInterface {
    * @throws GenOneBaseException
    */
   public void printUserMessage(byte[] message) throws GenOneBaseException {
+    actionCounter.incrementAndGet();
     String messageStr = SerialisationUtils.deserialiseFixedString(message);
     container.logInfo("Printing message '{}'", messageStr);

4.5. Testing the actionCounter Parameter

You have now completed the MessagePrinter implementation.

In order to test the behaviour of actionCounter you must once again build the HelloWorld2 Mission and run the MessagePrinterDemo Deployment Instance.

hgk mission build HelloWorld2
java -jar output/missions/HelloWorld2/MessagePrinterDemo/MessagePrinterDeployment/MessagePrinterDeployment.jar

Return to your active Lab or Bruno window.

4.5.1. Using Lab

Load the newly generated MDB by navigating back to the Config page, click the Replace.missiondb button and selecting the new MDB. This will include the latest changes you made to the Component Type.

helix lab config page replace mdb

Connect to your running Deployment Instance using the same steps as before.

Locate the printUserMessage Action and the 'actionCounter' Parameter in the Mission tree-view, and add command cards for each of them to the My Commands section.

Click on the actionCounter command card to expand its layout.

Issue a command to get the current value of the actionCounter Parameter by clicking its Get ⬇ button.

A value of 0 should be returned because that is the Parameter's initial value, as AtomicLong returns 0 by default.

Invoke the printUserMessage Action by expanding its command card, entering a string argument of your choice in hexadecimal format, then clicking the Invoke button.

Issue another get command on the actionCounter Parameter.

The returned value should have incremented by one since the last time it was issued as the printUserMessage Action has been invoked once since then.

4.5.2. Using Bruno

Select the get_parameter request, and click the refresh proto file methods button. Notice that we use a selection_id of 0 to target the first (and only) Parameter in the Component.

Send a request to get the value of the actionCounter Parameter by clicking the send request button. You should get the following response:

{
  "time": {
    "basic": 0,
    "fractional": 0
  },
  "value": "AAAAAA=="
}

Here the value parameter is the value of the 32-bit integer actionCounter Parameter, base64 encoded. You can decode it on the Linux command line with base64 and xxd:

> echo -n 'AAAAAA==' | base64 -d | xxd
00000000: 0000 0000                                ....

As you can see, a value of 0 is returned for the Parameter, as expected as this is the Parameter's initial value.

Invoke the printUserMessage Action by selecting and sending the invoke_action_print_user_message request.

Issue another get command on the actionCounter Parameter.

The returned value should have incremented by one since the last time it was issued as the printUserMessage Action has been invoked once since then.

5. Wrap Up

In this tutorial you have:

  • Added to a Component Type's implementation using the same steps that will be required when working on your own Component Types in the future.

  • Extended your understanding of Actions to include Arguments, and learned how they can be used to provide input to your Component Types.

  • Learned about Parameters and how they can be implemented using your Component Type Structure.

In the next tutorial you will be introduced to more capabilities you can add to Component Types. This will build on the understanding you have developed here using a different Component Type and Deployment Type.

Click here to move on to that now.