Tutorial: Building a KOS App for a Digital Product Rack

Introduction


Welcome to the tutorial on building your first KOS app! In this guide, you’ll learn how to create, configure, build, run, and debug a KOS application from start to finish.

Steps

This is the process that you will complete in this article.

ComponentContentEndpoints
KOS internalnone/api/kos/*
special “system” app/system/*/api/system/*
regular app/app/<appId>//api/app/<appId>/*
regular app/app/<appId>/*/api/app/<appId>/*/api/app/<appId>/*/api/app/<appId>/*/api/app/<appId>/*
KOS internalnone/api/kos/*
special “system” app/system/*/api/system/*

Target Audience

This tutorial assumes you have Java experience. The source code for these tutorials is available on GitHub.

Purpose of KOS and Why You Should
Use It

Before diving into this tutorial, let’s explore why KOS is a game-changer for smart devices. KOS is an embedded operating system with an SDK that simplifies the development and management of smart devices. It integrates essential components like the Linux kernel, Java runtime, and custom code to address common challenges in building software for your device. By using KOS, you can focus on innovation and functionality, knowing that the underlying system is robust and reliable. In this tutorial, you will see how quickly you can deliver value to your stakeholders. Let’s get started and see how KOS can transform your development experience!

Customer Request

This tutorial imagines a bookstore chain looking to modernize their bestseller display using a digital smart rack.

Their business objectives are:
Save time and money by transitioning from cardboard signage to over-the-air updates of digital content.
Enhance the customer experience through more engaging and dynamic displays.

Our solution is to build a smart rack application that will rotate a collection of image files promoting recent bestselling books.

Figure 1. Open Bestsellers

Let’s dive into creating an innovative and engaging digital product rack using KOS for our customer!

Video


Overview

In this video, we install and set NodeJS, which is used as a base for the entire development process.

We recommend using Node Version Manager (NVM) to install NodeJS, facilitating easy maintenance. NVM is installed or updated by running the install script. To do that, you may either download and run the script manually, or use the following cURL or Wget command:

curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

OR

wget -qO- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

After NVM is installed, Node can be installed using:

nvm install lts/hydrogen

Give a default alias to the hydrogen release for easy access later on:

nvm alias default lts/hydrogen

Now verify the Node and NVM installation and your system is ready for the next steps.

Transcript

This is just a placeholder to help you visualize how the content is displayed in the tabs. Feel free to edit this with your actual content.

Code

In this video, we install and set NodeJS, which is used as a base for the entire development process.

We recommend using Node Version Manager (NVM) to install NodeJS, facilitating easy maintenance. NVM is installed or updated by running the install script. To do that, you may either download and run the script manually, or use the following cURL or Wget command:

Install KOS Studio


What is KOS Studio?

The following articles will help you better understand Studio and guide you through the installation process on your development machine.

Code the App


Our digital rack project is quite straightforward. We need to loop through a collection of content and display it on the screen. This can be easily achieved by installing Linux on a Raspberry Pi and running a small Java Swing application. In fact, this example will demonstrate the KOS equivalent of this setup. While the example is simple, it allows us to introduce a few initial KOS concepts, use KOS Studio to install software and run in a simulator, and set up debugger support for remote debugging on any hardware target. We’ll also get a glimpse into the simplicity of building a dedicated-purpose device using KOS, where no install or startup scripts are required. We’ll simply push the play button and watch our device boot as a smart rack.

The System Application

Now that we have a way to display our digital content, we need to code the core component that launches it: the System Application.

Displaying Content

Before we get to the system application, let’s consider our options for displaying content on our rack. A common approach to displaying content is to use a web browser. It’s a rich display engine for a broad range of content, including device user interfaces. KOS has sophisticated browser integration support, including the ability to control multiple browsers across multiple devices, push real time data, handle asynchronous operations and even provides the ability for different browsers to communicate directly to each other. However, for our first example we want to focus on the basics such as learning how to use KOS Studio and debugger integration, so we’re going to display content in the simplest way possible, which is using Java Swing to rotate through images using a timer.

The class below uses basic Swing components to fill the screen with a Jframe that switches between images using a timer. As this is standard Swing programming, we show the class below without any additional description. This class will be used in our system application to display content.

Creating a system application for KOS is as simple as extending the SystemApplication class as shown below:

package com.bookstore.rack;
import javax.swing.SwingUtilities;
import com.tccc.KOS.core.service.app.BaseAppConfig;
import com.tccc.KOS.core.service.app.SystemApplication;
/**
 * System application for simple digital rack that has a display that
 * rotates content.
 *
 * @author David Vogt (david@kondra.com)
 * @version 2024-09-17
 */
public class RackApp extends SystemApplication<BaseAppConfig> {
    @Override
    public void started() throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new RackUI().setVisible(true);
            }
        });
    }
}

The User Interface

The provided Java code defines a class RackUI that displays the book rack content from the resources folder. It is launched in the started method of the System Application.

package com.bookstore.rack;
import java.awt.BorderLayout;
import java.awt.Color;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
public class RackUI extends JFrame {
    private JLabel imageLabel;
    private int currentIndex = -1;
    private final String[] imagePaths = {
        "/images/all.png",
        "/images/book1.png",
        "/images/book2.png",
        "/images/book3.png"
    };
    public RackUI() {
        // run full screen
        setExtendedState(JFrame.MAXIMIZED_BOTH);
        setUndecorated(true);
        // select the layout manager
        setLayout(new BorderLayout());
        // Set background color
        getContentPane().setBackground(Color.BLACK);
        // Image label to display the image content
        imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(JLabel.CENTER);
        add(imageLabel, BorderLayout.CENTER);
        // timer to rotate the image on the display
        Timer timer = new Timer(5000, (e) -> displayNextImage());
        timer.start();
        // show the first image
        displayNextImage();
    }
    private void displayNextImage() {
        currentIndex++;
        URL imageUrl = getClass().getResource(imagePaths[currentIndex % imagePaths.length]);
        ImageIcon icon = new ImageIcon(imageUrl);
        imageLabel.setIcon(icon);
    }
}

Code the App


In this section, we’ll walk you through setting up a Maven project to create and build a KOS-specific deployable file, known as a KAB, for deployment. We’ll cover the creation of a POM file for building the project and using a descriptor file to tell the KOS environment where to start. This tutorial assumes you are already familiar with Maven and POM files.

Step One: Create the POM file

This section will guide you through the pom.xml file setup specifically for developing a KOS application for your bestselling books rack. For the complete source of pom.xml, download complete pom.

But let’s take a look at the elements that are crucial to building a KOS app.

Step One: Create the POM file

The <properties> section centralizes project-wide settings and versions, ensuring consistency and ease of updates. This includes specifying the version of KOS to target, the version of Java required by KOS, and the versions of essential plugins.

    <!-- properties -->
    <properties>
        <KOS.version>0.0.0-SNAPSHOT</KOS.version>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <KOS-maven-plugin.version>1.0.7</KOS-maven-plugin.version>
        <maven-assembly-plugin.version>3.6.0</maven-assembly-plugin.version>
        <lombok.version>1.18.28</lombok.version>
    </properties>

Section 2: Include the KOS SDK

Problem: KOS provides numerous SDKs for building your app, but how do we know which versions of those SDKs to use so that they are compatible with each other and the version of KOS we are using?

Solution: We use the configuration management concept of a Bill of Materials (BOM). Each version of KOS (1.0, 1.1, 1.2, etc.) has a BOM that manages the specific compatible versions of SDKs. That way, when we add an SDK dependency, we don’t have to know the specific SDK version. We place these special BOM dependencies in the <dependencyManagement> element to ensure version consistency across this Maven module. If this were a multi-module app, as will be used in future tutorials, it would ensure consistency across all modules.

In this example, we’ve added KOS-bom as a <dependency> using the property KOS.version from our properties section.

    <!-- include KOS SDK BOM -->
    <dependencyManagement>
        <dependencies>
            <!-- KOS SDK -->
            <dependency>
                <groupId>com.KOSdev.KOS.sdk.bom</groupId>
                <artifactId>KOS-bom</artifactId>
                <version>${KOS.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

Then, in the <dependencies> element, we can add our core-api SDK without having to specify the version.

    <!-- project dependencies -->
    <dependencies>
        <dependency>
            <groupId>com.KOSdev.KOS.sdk.api</groupId>
            <artifactId>api-core</artifactId>
        </dependency>

Section 3: Plugin Management

The build and <pluginManagement> sections manage the versions of plugins used in the build process. This includes plugins for packaging your application JAR and data files into a ZIP file and converting the ZIP file into a KAB file for deployment. Remember, building jars and zips are just steps to build what a KOS environment really needs: KAB files.

    <!-- plugins to build zip and kab files -->
    <build>
        <pluginManagement>
            <plugins>
                <!-- assembly plugin for zip files -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-assembly-plugin</artifactId>
                    <version>${maven-assembly-plugin.version}</version>
                </plugin>
                <!-- KOS plugin for kab files -->
                <plugin>
                    <groupId>com.KOSdev.KOS.maven</groupId>
                    <artifactId>KOS-sdk-maven-plugin</artifactId>
                    <version>${KOS-maven-plugin.version}</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>

Section 4: Profiles

The <profiles> section defines build profiles that can be activated under specific conditions. The developer profile is activated by default and includes plugins for packaging your application into a KAB file, tailored for KOS development. Using the KOS-kab-maven-plugin, you can specify which files you need in your KAB and in which directories they should be placed.

    <!-- ====== Profiles ============================================================= -->
    <profiles>
        <profile>
            <id>developer</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <plugins>
                    <!-- Convert the contents of the build into a ZIP file -->
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <version>3.5.0</version>
                        <executions>
                            <execution>
                                <id>make-assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                                <configuration>
                                    <descriptors>
                                        <descriptor>assembly.xml</descriptor>
                                    </descriptors>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <!-- Convert the ZIP file to a KAB file -->
                    <plugin>
                        <groupId>com.KOSdev.KOS.maven</groupId>
                        <artifactId>KOS-kab-maven-plugin</artifactId>
                        <executions>
                            <execution>
                                <phase>package</phase>
                                <goals>
                                    <goal>kabtool</goal>
                                </goals>
                                <configuration>
                                    <type>KOS.system</type>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                </plugins>
            </build>
        </profile>
    </profiles>

Step Two: Create the Descriptor File

The descriptor.json file provides a standardized method for embedding metadata into KAB files for use in KOS. We will use it to describe the details of our applications to KOS. In later tutorials, we’ll see how descriptor.json can be used to support localization and even firmware updates. Developers can customize the descriptor.json while reserving the KOS.* namespace for standardized sections.

The descriptor.json File

{
  "KOS": {
    "app": {
      "appClass": "com.bookstore.rack.RackApp",
      "appId": "system"
    }
  }
}

appClass: Specifies to KOS the class that it should load to launch your application.

appId: Defines a unique ID for this application. Every application requires a unique ID to help allocate resources in KOS. We’re building a system application which always has an ID of system.

Step Three: Place the Content for the Image Rotator

Adding Images to Your Project

Add these four images to the src/main/resources/images directory.

rack/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── bookstore/
│   │   │           └── rack/
│   │   │               ├── RackApp.java
│   │   │               └── RackIU.java
│   │   └── resources/
│   │       ├── images/
│   │       │   ├── all.png
│   │       │   ├── book1.png
│   │       │   └── book2.png
│   │       │   └── book3.png
├── descriptor.json
├── pom.xml
└── README.md

Build Project


Run mvn clean install then navigate to the target directory within your project. You will find several files, including:

KAB File: samples-rack-1.0.0-SNAPSHOT.kab. This is the KOS Archive Bundle that packages your application for deployment.

Your target directory should contain the JAR and KAB files, along with any other directories that Maven may generate. This structure represents the skeleton of your project after a build.

Project Directory Structure

rack/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── bookstore/
│   │   │           └── rack/
│   │   │               ├── RackApp.java
│   │   │               └── RackIU.java
│   │   └── resources/
│   │       ├── images/
│   │       │   ├── all.png
│   │       │   ├── book1.png
│   │       │   ├── book2.png
│   │       │   └── book3.png
├── target/
│   ├── samples-rack-1.0.0-SNAPSHOT.jar
│   ├── samples-rack-1.0.0-SNAPSHOT.kab
├── descriptor.json
├── pom.xml
└── README.md

By following these steps, you built your KOS system application and generated the necessary artifacts. The KAB file, which packages your application, can then be imported into KOS Studio for further configuration and simulation. This process ensures that your application is properly packaged and ready for deployment on KOS-supported hardware.

Run Application


This section guides you through using KOS Studio to create and configure a runnable KOS image for your Java application. You’ll open KOS Studio, create a new image, configure it with the necessary settings, add your KAB file, and assign it to the appropriate section. You’ll run the configured image in the KOS Studio simulator to test its functionality. Finally, you’ll debug your applications to step through the code you’ve written. Following these steps is essential to running your application on your developer machine.

Step One: Create the image in Studio

Now that our Java application is written and bundled into a KAB file, let’s turn our attention to KOS Studio.

Follow these steps to create an image: 1. Open the KOS Studio application. 2. In the top-level menu bar, click on the “open image manager” button.

In this Images window, click on the “create new image” button.

In the popup dialog, enter a “Name” for this image, leave the “Parent Image” field blank, then click “Create”:

Now the Images window shows an entry for the image you just created:

Close the Images window and return to the main Studio window.

Step Two: Configure the image

On the main Studio screen, click the gear icon associated with the image you just created, which opens up the configuration dialog. This configuration window is perhaps the most important part of KOS Studio. It gives you and your team the ability to create any number of runnable images, each with a wide variety of options. Much time will be devoted to using it.

As you can see, there is a stack of six configuration items, also known as “cards”:

  • Sections: A section in KOS is an artifact container where you group your KABs and give them meaning by their names. More about Sections.
  • File Mappings: Defines mappings into the simulator file system.
  • Layers: A layer is a specific type of KAB file that allows you to customize OS-level changes for your image. You can choose from Market, Published, or local layers to add to your image.
  • Local Artifacts: The Local Artifacts card in the image configuration window lets users select a locally available KAB for use in the image. This is useful for testing changes or using artifacts that are not yet published.
  • Hardware Settings: The Hardware Settings card allows users to configure their simulation and node settings, including selecting hardware profiles, configuring port mappings, and setting developer flags.
  • KOS Version: The KOS Version card is the first step in setting up your image. Here, you can specify which KOS version and add-ons you want to use.

The “KOS Version” item has red text, meaning that it needs attention.

Configure the KOS Version

Our next step is to tell Studio which release of KOS we want to use, which will satisfy the current alert.

  1. Click on the “KOS Version” card.
  2. Click on the “Configure new release” button.
  3. On the left-hand side, navigate and then select the desired KOS release.
  4. Give this selection a name and an optional note.
  5. Check Graphics.
  1. Click the “Submit” button.
  2. Then select the newly-created release.

At this point, the “KOS Version” section is no longer red, meaning it is configured properly.

Configure the local artifact

  1. Click on the “Local Artifacts” card
  2. Click the “Select local artifact” button.
  3. Navigate to and select the KAB file created earlier by our Java code.
  1. Click the Select button, where you should see:

Configure the local artifact

A section in KOS is the artifact container. It is where you group your KABs and give them meaning by their names.

  1. Open the “Sections” card.
  2. Drag the “samples-rack-1.0.0-SNAPSHOT.kab” item from “Local Artifacts” to the KOS.system “Section”.
  1. Close the configuration window.

Step Three: Execute the image

To run your KOS application in Studio’s built-in simulator:

  1. Open the “Sections” card.
  2. Drag the “saOn the main Studio screen, find your “Bestseller Rack” image entry.
  3. Ensure that “Simulator” is selected.
  4. Click the “run now” (play) icon.mples-rack-1.0.0-SNAPSHOT.kab” item from “Local Artifacts” to the KOS.system “Section”.

The application first downloads all necessary artifacts, showing the status in the Connections window. The first time you run an application it may take a while to download the required packages. Subsequent executions open much faster.

When downloading is finished, the application will begin to load. You’ll see the simulator starting up:

Figure 14. Simulator When the simulator has finished, you should see your bestsellers rack application
Figure 15. App running

Try dropping a break point in your app and give it a whirl!

Congratulations, your first KOS application is up and running! To make changes to your app, simply stop the simulator, update your code, rebuild the KAB file, and restart the simulator. It’s that easy!

This lesson has equipped you with the skills to effectively use KOS Studio to create, configure, and test a runnable KOS image for your Java application. By following these steps—opening KOS Studio, creating a new image, configuring it with necessary settings, adding your KAB file, assigning it to the appropriate section, running it in the KOS Studio simulator, and debugging your code—you’ve laid the groundwork for successfully running your application on your developer machine. Great job!

Conclusion

In this tutorial, we guided you through creating your first KOS application for a smart rack. Starting with an introduction to KOS, we installed KOS Studio, coded the core application, set up a Maven project, and built the KAB file using the KAB plugin. We then configured and tested the application in KOS Studio, ensuring it runs smoothly before deployment.

By the end of the tutorial, you built a functional smart rack application and gained insights into KOS’s potential. You’re now equipped with the skills to embark on more ambitious projects, leveraging KOS to create innovative, reliable, and efficient solutions for various smart device applications.

FAQ


Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Next

Button Title