Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,30 @@ Pi4J :: Java I/O Library for Raspberry Pi :: Examples

Various examples demonstrating the use of Pi4J core and/or drivers library.

## The Environment
If setting up a new Raspberry Pi, see the Pi4J documentation for assistance.
[Prepare a Raspberry Pi](https://www.pi4j.com/prepare/)
## Setup

To move this code repository to your Raspberry Pi use the git clone command.
If not familiar with 'git' minimal reading is recommended.
git clone https://github.com/Pi4J/pi4j-examples "target directory"
If setting up a new Raspberry Pi, see the Pi4J documentation for assistance:
[Prepare a Raspberry Pi](https://www.pi4j.com/prepare/).

Each example device has a README with build and usage documentation.
Running the examples requires __Java 25__, __Maven__ and __git__ to be installed; for
instructions, please refer to: [Install Java and Tools](https://www.pi4j.com/prepare/install-java/).

To copy the code for all the examples to your Raspberry Pi, use the git clone
command:

```
git clone https://github.com/Pi4J/pi4j-examples
cs pi4j-examples
```

You can now build the examples running the following command:

```
mvn clean package
```

Commands for running individual examples are typically provided in the README.md file for each example
linked below.

## Pi4J Concept Examples

Expand Down
57 changes: 48 additions & 9 deletions src/main/java/com/pi4j/examples/sensor/homeassistant/README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,49 @@
# HomeAssistant Pi4J Sensor Wireup Example

![Sensor data rendered on a 1602 LCD dispaly](sensor_display_2004.jpg)
# HomeAssistant Pi4J Sensor Server Example

A simple REST server that reports the measurements for all
auto-detected I2C sensors as a simple JSON object.

## Hardware Setup

Connect any available I2C sensor(s) and a HD44780+PCF8574 based 20x4 LCD to I2C bus 1
(Pins 1-3 for power, SDA and SCL and pin 6 for Ground).
(Pins 1-3 for power, SDA and SCL and pin 6 for Ground), as shown in the picture below.

![Pi4 wired up to a breadboard with a BME280, SCP42 and 2004 LCD](sensor_wireup_2004.jpg)


## Example Code
The CAD file for the open case can be found here: [breadboard-2004-open-pi-case](https://www.tinkercad.com/things/03pwEHJODWy-breadboard-2004-open-pi-case)

## The Example Code

The example code consists of the following files:

- SensorServer.java: Provides sensor values in JSON format (compatible with HomeAssistant) via a tiny
HTTP server

- SensorServer2004App.java: Additionally renders the values on a 20x4 LCD
- SensorServer2004App.java: Additionally renders the values on a 20x4 LCD (it should be straight forward to adapt this
code to use a different display)

- TinyWebServer: A tiny utility implementing a server socket HomeAssitant can connect to.

## Usage
## Running the Server

If not already done, please follow the general example setup instructions in
the [main README](../../../../../../../../README.md#setup) file.

After these steps, a headless server can be started from the pi4j-examples directory unsing the following maven
command:

```
mvn exec:java -Dexec.mainClass="com.pi4j.examples.sensor.homeassistant.SensorServer"
```

Alternatively, connect a 20x4 LCD to the Pi4J I2C bus and start the server with the following command:

When started, the server will print intstructions how to use it, similar to this:
```
mvn exec:java -Dexec.mainClass="com.pi4j.examples.sensor.homeassistant.SensorServer2004App"
```

When started, the server will print instructions on how to use it, similar to this:

```
Sensors found:
Expand All @@ -38,5 +60,22 @@ configuration snippet: http://192.168.178.197:8147/config
Measurements: http://192.168.178.197:8147/measurements

This help text: http://192.168.178.197:8147

```

The "2004" server will additionally render the sensor values on a 20x4 LCD, as shown in the image below.

![Pi4 sensor data display](sensor_display_2004.jpg)

## Home Assistant Integration

To integrate the server with Home Assistant, you can use the configuration snippet provided by the server.

View the URL from the "configuration snippet" line in a browser and paste the content it into your
Home Assistant `config.yaml` file in the `rest:` section (which might need to be added if it does not exist already).

This will allow Home Assistant to connect to the server and retrieve sensor data. A rest integraton should
appear automatically in Home Assistant, and it should provide a debug logging option, which comes quite
handy if anything goes wrong.

Unfortunately, resolving host names in the local network seemed unreliable in HomeAssistant. It's probably best to
assign a fixed IP address locally or in the router, so this won't change after a reboot.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import com.pi4j.examples.sensor.display.SensorAggregator;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

public class SensorServer {
Expand All @@ -17,6 +19,7 @@ public class SensorServer {
private final SensorAggregator sensorAggregator;
private final int httpPort;
private final Object lock = new Object();
private String namePrefix;

private Map<SensorDescriptor.Kind, Double> currentReadings;
private String address;
Expand All @@ -25,6 +28,12 @@ public SensorServer(SensorAggregator sensorAggregator, int httpPort) {
this.sensorAggregator = sensorAggregator;
this.httpPort = httpPort;

try {
namePrefix = Files.readString(Path.of("/etc/hostname")).trim();
} catch (IOException e) {
namePrefix = "pi4j_sensor_server";
}

System.out.println("Sensors found:");
System.out.println(sensorAggregator.getSensorList());

Expand All @@ -34,7 +43,7 @@ public SensorServer(SensorAggregator sensorAggregator, int httpPort) {

System.out.println("Reading initial sensor values...");
currentReadings = sensorAggregator.readAveragedMeasurements();
System.out.println("Initial sensor values aquired: " + currentReadings);
System.out.println("Initial sensor values acquired: " + currentReadings);
System.out.println();
}

Expand Down Expand Up @@ -93,12 +102,12 @@ void renderConfig(PrintWriter out) {
out.println("# Add this snippet to the 'rest:' section in your HomeAssistant config.yaml:");
out.println("# rest:");
out.println(" - resource: \"" + address +"/measurements\"");
out.println(" sensor:\n");
out.println(" sensor:");
synchronized (lock) {
for (SensorDescriptor.Kind kind: currentReadings.keySet()) {
String deviceClass = getHomeAssistantDeviceClass(kind);
if (deviceClass != null) {
out.println(" - name: \"" + kind + '"');
out.println(" - name: \"" + namePrefix + "_" + kind + '"');
out.println(" value_template: \"{{ value_json['" + kind + "'] }}\"");
out.println(" device_class: " + deviceClass);
out.println(" unit_of_measurement: \"" + kind.measurementUnit + '"');
Expand All @@ -112,15 +121,17 @@ void renderHelp(PrintWriter out) {
out.println();
out.println("HomeAssistant YAML");
out.println("configuration snippet: " + address + "/config");
out.println("Measurements: " + address + "/measurements\n");
out.println("Measurements: " + address + "/measurements");
out.println();
out.println("This help text: " + address);
}

/** Returns the home assistant device class for the given sensor kind. */
static String getHomeAssistantDeviceClass(SensorDescriptor.Kind kind) {
return switch(kind) {
case CO2 -> "carbon_dioxide";
case LIGHT, LIGHT_BLUE, LIGHT_RED, LIGHT_GREEN -> "illuminance";
case CO2, DISTANCE, HUMIDITY, PRESSURE, TEMPERATURE -> kind.toString();
case DISTANCE, HUMIDITY, PRESSURE, TEMPERATURE -> kind.toString();
default -> null;
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
import javafx.util.Pair;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
Expand All @@ -26,10 +24,12 @@ public TinyWebServer(int port) throws IOException {

/** Returns the URL of this server as a String */
public String getUrl() {
// This was recommended on stack overflow to get the local IP. Unfortunately, resolving host names in the local
// network seemed unreliable in HomeAssistant. It's probably best to assign a fixed IP address locally or in
// the router, so this won't change after a reboot.
try (Socket socket = new Socket()) {
// Get our own address, see https://stackoverflow.com/a/41822127/1401879
socket.connect(new InetSocketAddress("google.com", 80));
return "http:/" + socket.getLocalAddress() + ":" + port;
return "http://" + socket.getLocalAddress() + ":" + port;
} catch (IOException e) {
throw new RuntimeException(e);
}
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading