Java on the Raspberry Pi-Part 2: Control of GPIOS With a Spring-Rest service products Code Einting Login Password?Thank you for registration for your assessment!Thanks for your review!

Java on the Raspberry Pi-Part 2: Control of GPIOS With a Spring-Rest service products Code Einting Login Password?Thank you for registration for your assessment!Thanks for your review!

The Java Development Kit (JDK) in version 11 already contains the operating system version Raspberry Pi Os Full (32-bit).In order to develop Java applications, however, a IDE helps us to write applications that are easy to wait.As described in the previous article [1], Visual Studio Code can be used on the Raspberry Pi.Alternatively, applications in Visual Studio Code can also be developed on a PC and then compiled and executed on the Raspberry Pi.

For this article we will write the code directly on the Raspberry Pi.We need some additional tools for this, so we install them first.

Maven

We will use Maven to create the application on our Raspberry Pi.Maven compils the code together with the necessary dependencies into a single JAR file.This is thanks to the POM configuration file.XML possible, which is located in the regular directory of the project.

Maven is installed with a single command.Then we check the installation by querying the version as follows:

$ sudo apst install maven $ mvn -vapache maven3.6.0maven Home:/USR/Share/Maven

Pi4j

Um die GPIOs und verschiedene daran angeschlossene elektronischen Komponenten zu steuern, verwenden wir die Pi4j-Bibliothek, die eine Brücke zwischen unserem Java-Code und den GPIO-Pins (GPIO = General Purpose Input/Output) des Raspberry Pi schlägt.Um die volle Unterstützung der Pi4j-Bibliothek auf dem Raspberry Pi zu erhalten, müssen wir eine zusätzliche Software installieren.We also only need a single command for this:

$ curl -SSL https: // pi4j.com/install |Sudo Bash

Wiringpi update

One last step in preparation is required. Wenn Sie einen Raspberry Pi◦4 verwenden, müssen Sie die von Pi4j verwendete native Bibliothek WiringPi zur Ansteuerung der GPIOs aktualisieren.Since the architecture of the system-on-chip (SOC) has changed with version 4, a new version of WiringPi is required. Leider wurde dieses Projekt im letzten Jahr „deprecated“, aber dank der Open-Source-Community ist eine inoffizielle Version verfügbar, die durch ein von Pi4j bereitgestelltes Skript installiert werden kann.To do this, carry out the command:

Sudo pi4j -wiringpi

The command moves into the Github project, compiled and installs it on your Raspberry Pi in one slip.If you query the version, you will see that you are from standard version 2.50 on 2.60 has been upgraded:

$ gpio -vgpio version: 2.50$ sudo pi4j –wiringpi$ pi4j -v-------------------------------------------- THE Pi4j PROJECT-------------------------------------------- PI4J.Version: 1.3 pi4j.TIMESTAMP: 2021-01-28 04:14:07 ---------------------------------- Wiringpi.Path:/usr/lib/libwiringpi.So/usr/local/lib/libwiringpi.So Wiringpi.Version: 2.60 -------------------------------------

The application

The complete code of this application is available in the Github repository of this article [2] in the elector/2106 folder.This project is a proof-of-concept application that controls the GPIOs via a rest of the fuel service.It uses the Spring framework, software that offers many tools for creating powerful applications with minimal code (Fig. 1).

The process for creating the various files made of this project is described below.If this does not work, the repository code should work out-of-the-box.

The finished project is downloaded from Github as follows:

Pi@Raspberrypi: ~ $ git clone https: // github.com/fdelporte/elector cloning into 'elector'...Remote: Enumerating Objects:34, Done.Remote: Counting Objects: 100% (34/34), Done.Remote: Compressing Objects: 100% (24/24), Done.Remote: Total34 (Delta 2), Reused34 (Delta 2), Pack-Reused 0unpacking Objects: 100% (34/34), Done.Pi@Raspberrypi: ~ $ CD ELICTION/2106PI@Raspberrypi: ~/Elector/2106 $ LS -LTOTAL 8-RW-R-- 1 PI PI 1720 Feb 15 14:23 Pom.XMLDRWXR-XR-X3 Pi Pi 4096 Feb 15 14:23 SRC

What are Spring and his tools?

Spring is a framework that simplifies and accelerates the development of (business) Java applications.Spring Boot is a layer that puts on Spring and provides "finished" packages that make it possible to create independent jumping-based applications that can be "simply executed".This is achieved by a principle of "Convention Over Convention", which means that by default everything works according to a predefined convention.If you want to do something differently, you can configure your own way.

The Spring Boat website mentions the most important skills [3]:

Easy creation of independent jumping applications.

Enables the embedding of a web server in your application (Tomcat, Jetty or Undertow).

Provides "starter" dependencies to simplify your build configuration.

Configures Spring and Libraries of third -party providers automatically whenever this is possible.

Offers production -ready functions such as metrics, health checks and externalized configuration.

No need for code generation or XML configuration.

Finally there is Spring Initializr [4], an online tool for the quick creation of a starter application that contains all the necessary spring boat packages.

First steps

To create this project from scratch, we first use Spring Initializr, a web -based configuration form for creating an entry -level package.Follow the link in [4] and enter the information shown in Figure 2 in the form.

Make sure that you also click the Dependcies button on the right side.In the window that opens we have to add the dependency Spring Web that can be found quickly via the search field.By clicking on this entry, the dependency is added to the project.If an unwanted dependency has been accidentally added, it can be removed again by clicking on the red button (far right).

Adding the dependency Spring Web enables a residual application [5] to be created that enables us to connect to the application via websites in the browser.

A click on the Generates button delivers a ZIP file with a finished Maven project.After it has been unpacked in a suitable directory, it can be opened in Visual Studio Code [6] both on the Raspberry Pi and on a PC. Verwenden Sie einfach File -> Open folder...and choose the unpacked folder.Next you are looking for the Javaspringrestepplication file.Java (under SRC/Main/Java).In the context menu of this file name, select the Run option so that the application is started (Fig.3).

Installation of Visual Studio Code does not have the required Java support, a pop-up window appears that calls for installation.

In the terminal window we receive the output in Listing◦1 (here without time stamps).What does this edition tell us?

The JVM (Java Virtual Machine) ran for seven seconds, of which 4.5◦s were required to start the application.

Tomcat (the web server) is embedded in the application and runs on port 8080.

So we open a browser and go to http: // localhost: 8080/(Fig. 4).

Big disappointment!We get an error page.But this is only because we have not yet created anything that could be displayed on this page!At the same time, however, this error page proves that our application works and works as a web server.She just doesn't know what to tell us.

Java auf dem Raspberry Pi - Teil 2: Steuerung von GPIOs mit einem Spring-REST-Service Produkte Code einbetten Login Passwort vergessen? Zur Registrierung Vielen Dank für Ihre Bewertung! Vielen Dank für Ihre Bewertung!

We build our own application

We will now expand this Spring starter package with the functionality that we want in our application, namely the control of the GPIOs via Java code. Dazu müssen wir die Pi4j-Bibliothek in unser Projekt einbinden.Since we can use the full set of Java methods of this library, we do not have to control the hardware ourselves.However, it should be borne in mind that due to the dependency of this library from the Raspberry Pi we cannot fully execute or test this application on the PC.To do this, the created Jar file must be carried out on the Raspberry Pi.In the code examples that are made available here, every variable and method in Javadoc style (starting with /**) is commented on to explain their purpose.

Add dependencies

We add the PI4J Core addiction to POM with Spring Initializr.add XML file to access the PI4J methods:

com.pi4j

Pi4j-Core

1.3

compile

And if we are already there, we can also add the OpenAPI addiction (SpringDoc-Openapi ui), which we will later use for testing the rest services:

org.Springdoc

Springdoc-openapi-ui

1.5.1

Add an information rest controller

Das erste, was wir mit dieser Anwendung zeigen werden, sind die von der Pi4j-Bibliothek bereitgestellten Informationen über unseren Raspberry Pi.We first create a package controller with a file inforest controller.Java. In Visual Studio Code klicken Sie einfach mit der rechten Maustaste auf den Eintrag Java\be\webtechie\Javaspringrestgpio und wählen New Folder.You baptize the new folder controller, right -click on the folder and choose New File.Name the File inforest controller.Java.

You can find the complete code in the material for the artíkel, but Listing 2 shows a short neckline.Each method is a residual mapping that returns a certain set of key value pairs with information about the Raspberry Pi.

Add the GPIO manager

Before we can create the GPIO REST controller, we have to.Java hinzufügen, um die Pi4j-Aufrufe zu verarbeiten.This is stored in a manager package, which was created as a new folder and new file as before. Dieser Manager soll die initialisierten GPIO-Pins speichern und die Pi4j-Methoden aufrufen, die mit den GPIOs interagieren.A short section of the code in Listing◦3 can also be seen here, while the complete code for this class can be found in the repository.In this class, @service is used, which the Spring framework shows to keep a single instance of this object in the memory.We have a list of the GPIOs provided at any time.

Add the GPIO REST controller

Finally, we add a GPIO controller to the controller package (folder) with a residual interface.This file is called GpiorestController.Java und stellt die Pi4j-GPIO-Methoden zur Verfügung, die wir in der Klasse GpioManager.Java definiert haben.Here, too, a section of the code in Listing◦4 is shown, while the complete code is available in the repository.

Execution of the application

This step can be taken on both the PC and on the Raspberry Pi.In the first case, it is best to start the application from Visual Studio Code, because it makes the installation of Maven on the PC superfluous.

Da wir die Springdoc-openapi-ui-Abhängigkeit der pom.have added XML file, the application provides a very useful swagger website for testing the remaining services.Swagger is another open source project that generates a simple web page interface for testing our Java codes by automatically visualizing the controllers created by us.

There are two ways to start the application.In Visual Studio Code it can be started with Run (Raspberry Pi or PC).An alternative for the Raspberry Pi is to transfer the application with MVN Package to a JAR file.Once this has happened, the file is started as follows from the command line:

Java -jar target/Javaspringrestgpio-0.0.1-snapshot.jar

In a browser on the Raspberry Pi, open the Swagger page with http: // Localhost: 8080/Swagger-UI.HTML.Alternatively, you can on any PC in the same network http: //

: 8080/Swagger-UI.HTML verwenden.The two controllers with their methods are shown as shown in Figure5.

Testing the information rest controller

We can click on the buttons of the Swagger page and run the available options, for example in the Info-Rest controller section next to the INFO/HARDWARE method click on GET.Then click on Try IT Out and Execute, so that the answer is displayed in the Response Body section.

All of these methods can also be accessed directly from the browser. Hängen Sie einfach den Methodennamen an die URL: Für info/hardware geben Sie einfach http://localhost:8080/info/hardware ein, und für info/Java wäre es http://localhost:8080/info/Java.The data from the calling of these methods are displayed in JSON format, as can be seen in Figure 6.

Test of the GPIO REST controller with LED and button

In order to demonstrate how the application can interact with the GPIOs, we use a very simple Breadboard structure as shown in Figure 7:

LED on GPIO PIN 15, BCM controller PIN 22, WiringPi NR.3

Button on GPIO PIN 18, BCM controller PIN 24, WiringPi NR.5

In order to be able to control the connected LED and to read out the button, we must first initialize the GPIOs.The method/GPIO/commission/digital/output is used to configurate the output. Kehren Sie auf die Seite http://localhost: 8080/Swagger-UI.HTML zurück, klicken bei dieser Methode auf GET, Try it out und tragen dann3 in address sowie LED in string ein.Confirm the configuration by Execute (Fig. 8 Left).

The entrance is configured with the method/GPIO/commission/digital/input. Klicken Sie bei dieser Methode auf GET, Try it out und tragen dann5 in address sowie Button in string ein.Confirm the configuration by Execute (Fig. 8 right).

As soon as the GPIOs are initialized, we can get a list of the GPIOs with the method/GPIO/Commission/List.Simply use GET, Try it out and execute or enter the URL http: // localhost: 8080/GPIO/provision/list directly in the browser (Fig. 9).

Now that we have checked that the GPIOs are ready for use, we can use the LED with the method/GPIO/Digital/Toggle to switch on and off by repeatedly clicking the Execute button (Figure◦10).

There is another method that can switch on the LED for a certain time, for example for 2S (Fig. 11).The duration must be specified in milliseconds

The state of the button can be queried via the Swagger interface, but is also available directly via the URL HTTP: // Localhost: 8080/GPIO/State/5.In the case of Figure 12, the button is pressed and gives a 1 back.

Anyone who rests, who rusts, who remains, continue researching!

In dieser Anwendung wurden nur einige der Pi4j-Methoden als REST-Services gezeigt, um die Möglichkeiten und die Leistungsfähigkeit dieses Ansatzes zu zeigen.Depending on the project you want to build, you can expand or revise this example to tailor your needs.

Die Pi4j-Bibliothek wird derzeit neu geschrieben, um eine noch bessere Unterstützung für den Raspberry Pi 4 und zukünftige Versionen zu bieten.As a result, it is brought up to date with the latest versions of Java.In the meantime, you can get started with the current version and create applications where you want to integrate the control of the hardware via a residual API.

Fragen zu diesem Artikel, Java oder Raspberry Pi?Haben Sie technische Fragen oder Kommentare zu diesem Artikel? Dann kontaktieren Sie den Autor direkt über Javaonraspberrypi@webtechie.Be or the editor of Editor@Elector.com.Translation: Rolf Gerstendorf