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
20 changes: 6 additions & 14 deletions pi4j-core/src/main/java/com/pi4j/common/Lifecycle.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@

import com.pi4j.context.Context;
import com.pi4j.exception.InitializeException;
import com.pi4j.exception.ShutdownException;

import java.io.Closeable;

/**
* Defines the managed startup and shutdown phases for Pi4J components such as I/O providers and platforms.
* Components are brought online with {@link #initialize(Context)} and torn down with
* {@link #shutdownInternal(Context)}, both bound to the active {@link Context}.
* close().
*
* @param <T> the self-type returned by the lifecycle methods, enabling fluent chaining on the implementing component
*/
public interface Lifecycle<T> {
public interface Lifecycle<T> extends Closeable {

/**
* Initializes this component against the given Pi4J context, acquiring any resources it needs to operate.
Expand All @@ -22,15 +23,6 @@ public interface Lifecycle<T> {
*/
T initialize(Context context) throws InitializeException;

/**
* Shuts this component down as part of the registry's teardown, releasing resources acquired during
* initialization. This method is called by the registry internally when the registry is shutting down and
* should not be called by users directly. To shut down an IO instance, call {@code close()} instead, which
* ensures the instance is not just shut down and closed but also properly unregistered.
*
* @param context the active Pi4J {@link Context} this component is being shut down within
* @return this component instance, after shutdown
* @throws com.pi4j.exception.ShutdownException if an error occurs during shutdown.
*/
T shutdownInternal(Context context) throws ShutdownException;
@Override
void close();
}
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ private void shutdownProvider(Provider provider) throws ShutdownException {
try {
logger.trace("calling 'shutdown()' provider [id={}; name={}; class={}]",
provider.id(), provider.name(), provider.getClass().getName());
provider.shutdownInternal(context);
provider.close();
} catch (ShutdownException e) {
logger.error("unable to 'shutdown()' provider: [id={}; name={}]; {}",
provider.id(), provider.name(), e.getMessage());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,18 @@ <T extends IO> T shutdown(T instance)
if (instance == null)
throw new IllegalArgumentException("An IO instance cannot be NULL.");

// Make sure instance wasn't already shut down / prevent a loop with close()
if (this.instances.remove(instance.id()) == null) {
return instance;
}

// shutdown instance
try {
long start = System.currentTimeMillis();

instance.shutdownInternal(context);
// Close is required to be idempotent. So we should be free to call close again, even if this call
// comes from close(). Ideally, we wouldn't have this ambiguity but relying on this seems to be the
// simplest solution until we provide a callback to the lifecycle initialization.
instance.close();
long took = System.currentTimeMillis() - start;
if (took > 10) {
logger.info("Shutting down of IO {} took {}ms", instance.getId(), took);
Expand All @@ -117,7 +124,6 @@ <T extends IO> T shutdown(T instance)
// remove the shutdown instance from the registry
removeFromMap(instance);

this.instances.remove(instance.id());
return instance;
}

Expand Down
43 changes: 15 additions & 28 deletions pi4j-core/src/main/java/com/pi4j/io/IOBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.pi4j.common.IdentityBase;
import com.pi4j.context.Context;
import com.pi4j.exception.InitializeException;
import com.pi4j.exception.ShutdownException;
import com.pi4j.provider.Provider;

import java.io.Closeable;
Expand All @@ -27,7 +26,7 @@ public abstract class IOBase<IO_TYPE extends IO, CONFIG_TYPE extends IOConfig, P
protected PROVIDER_TYPE provider;
private Context context;
// close() requires idempotency.
private boolean closed = false;
protected boolean closed = false;
Comment thread
stefanhaustein marked this conversation as resolved.
Resolved

@Override
public PROVIDER_TYPE provider(){
Expand Down Expand Up @@ -63,26 +62,25 @@ public IO_TYPE description(String description){
}

/**
* Closes the driver by calling this.context().shutdown(this.getId()), which in turn calls
* the local shutdownInternal(context) method here via DefaultRuntimeRegistry.remove().
* Closes the driver and calls this.context().shutdown(this), which removes this IO instance from the context
* registry.
* <p>
* Basically, for Pi4J, this constitutes an idempotent user convenience method for
* this.context().shutdown(this.getId())
* Note for subclass implementations: As context.shoutdown(IO) might be called directly for historical reasons,
* it needs to call this method again. To prevent an infinite cycles, it's important that the idempotency aspect
* of the close contract is strictly observed.
* <p>
* Subclasses should typically override the local shutdown method with implementation-specific shutdown
* behaviour. Behaviour added here will not be triggered by context.shutdown()
*/
@Override
public final void close() {
public void close() {
// The closed check ensures idempotency, as required by the close method contract.
if (!closed) {
// The null check accounts for contextless tests or somehow just closing without initializing,
// although we probably should make context a required ctor parameter, see #719
if (this.context != null) {
this.context.shutdown(getId());
} else {
shutdownInternal(null);
}
if (closed) {
return;
}
closed = true;
// The null check accounts for contextless tests or somehow just closing without initializing,
// although we probably should make context a required ctor parameter, see #719
if (this.context != null) {
this.context.shutdown(this);
}
}

Expand Down Expand Up @@ -111,17 +109,6 @@ public IO_TYPE initialize(Context context) throws InitializeException {
return (IO_TYPE) this;
}

@Override
public IO_TYPE shutdownInternal(Context context) throws ShutdownException {
// Close is supposed to be idempotent. We interpret this here to include effective shutdowns by
// other means, i.e. the infrastructure calling this method.
this.closed = true;
if (context != this.context) {
throw new IllegalArgumentException("The context parameter and the local context don't match.");
}
return (IO_TYPE) this;
}

@Override
public Descriptor describe() {
return super.describe().category("IO");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
package com.pi4j.io.gpio.digital;

import com.pi4j.context.Context;
import com.pi4j.event.EventDelegate;
import com.pi4j.event.EventManager;
import com.pi4j.exception.ShutdownException;
import com.pi4j.io.gpio.GpioBase;

import java.util.function.Consumer;
Expand Down Expand Up @@ -90,12 +88,12 @@ protected void dispatch(DigitalStateChangeEvent event){
}

@Override
public DIGITAL_TYPE shutdownInternal(Context context) throws ShutdownException {
// remove all listeners
public void close() {
if (closed) {
return;
}
stateChangeEventManager.clear();

// return this instance
return super.shutdownInternal(context);
super.close();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,13 @@ public DigitalState state() {
* Before delegating to the base shutdown logic, drives the output to the configured shutdown state if
* {@link DigitalOutputConfig#shutdownState()} is set and not {@link DigitalState#UNKNOWN}.
*
* @throws ShutdownException if the shutdown state cannot be written or base shutdown fails
* Throws a ShutdownException if the shutdown state cannot be written or base shutdown fails
*/
@Override
public DigitalOutput shutdownInternal(Context context) throws ShutdownException {
public void close() {
if (closed) {
return;
}
// set pin state to the shutdown state if a shutdown state is configured
if (config().shutdownState() != null && config().shutdownState() != DigitalState.UNKNOWN) {
try {
Expand All @@ -90,7 +93,7 @@ public DigitalOutput shutdownInternal(Context context) throws ShutdownException
throw new ShutdownException(e);
}
}
return super.shutdownInternal(context);
super.close();
}

/**
Expand Down
7 changes: 5 additions & 2 deletions pi4j-core/src/main/java/com/pi4j/io/pwm/PwmBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,10 @@ public Pwm initialize(Context context) throws InitializeException {
}

@Override
public Pwm shutdownInternal(Context context) throws ShutdownException {
public void close() {
if (closed) {
return;
}
// apply a shutdown value if configured
if (this.config.shutdownValue() != null) {
try {
Expand All @@ -131,6 +134,6 @@ public Pwm shutdownInternal(Context context) throws ShutdownException {
throw new ShutdownException(e);
}
}
return super.shutdownInternal(context);
super.close();
}
}
6 changes: 2 additions & 4 deletions pi4j-core/src/main/java/com/pi4j/provider/ProviderBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
import com.pi4j.context.Context;
import com.pi4j.exception.InitializeException;
import com.pi4j.exception.LifecycleException;
import com.pi4j.exception.ShutdownException;
import com.pi4j.extension.ExtensionBase;
import com.pi4j.io.IO;
import org.slf4j.Logger;
Expand Down Expand Up @@ -71,20 +70,19 @@ public PROVIDER_TYPE initialize(Context context) throws InitializeException {
* the remaining shutdowns.
*/
@Override
public PROVIDER_TYPE shutdownInternal(Context context) throws ShutdownException {
public void close() {

// TODO :: ABSTRACT PROVIDER IO INSTANCE SHUTDOWN VIA PROXY IMPL

// perform a shutdown on each digital I/O instance that is tracked in the internal cache
Map<String, IO> instances = context.registry().allByProvider(this.id(), IO.class);
instances.forEach((address, instance)->{
try {
instance.shutdownInternal(context);
instance.close();
} catch (LifecycleException e) {
logger.error(e.getMessage(), e);
}
});
return (PROVIDER_TYPE)this;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.pi4j.plugin.ffm;

import com.pi4j.common.Lifecycle;
import com.pi4j.context.Context;
import com.pi4j.exception.Pi4JException;
import com.pi4j.exception.ShutdownException;
Expand Down Expand Up @@ -74,6 +75,6 @@ public void initialize(PluginService service) {

@Override
public void shutdown(Context context) throws ShutdownException {
Arrays.stream(this.providers).forEach(provider -> provider.shutdownInternal(context));
Arrays.stream(this.providers).forEach(Lifecycle::close);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -170,11 +170,13 @@ public DigitalInput removeListener(DigitalStateChangeListener... listeners) {
* Stops all event watchers, waits for their threads to finish their current native {@code poll()}
* cycle, then delegates to {@link FFMGpioLine#close()} to release the GPIO line.
*
* @throws ShutdownException if waiting for the watcher threads or closing native resources fails
* Throws a ShutdownException if waiting for the watcher threads or closing native resources fails
*/
@Override
public DigitalInput shutdownInternal(Context context) throws ShutdownException {
super.shutdownInternal(context);
public void close() throws ShutdownException {
if (closed) {
return;
}
logger.info("{}-{} - closing GPIO offset.", line.deviceName, line.mask);
try {
logger.trace("{}-{} - Stopping event watchers", line.deviceName, line.mask);
Expand Down Expand Up @@ -214,7 +216,7 @@ public DigitalInput shutdownInternal(Context context) throws ShutdownException {
line.close();
}
logger.info("{}-{} - GPIO offset is closed.", line.deviceName, line.mask);
return this;
super.close();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,21 @@ public DigitalOutput initialize(Context context) throws InitializeException {
* <p>
* Closes the requested line file descriptor, releasing the GPIO line back to the kernel.
*
* @throws ShutdownException if closing the native line file descriptor fails
* Throws a ShutdownException if closing the native line file descriptor fails
*/
@Override
public DigitalOutput shutdownInternal(Context context) throws ShutdownException {
super.shutdownInternal(context);
public void close() {
if (closed) {
return;
}
logger.info("{}-{} - closing GPIO BCM.", line.deviceName, line.mask);
try {
line.close();
line.close();
} catch (Exception e) {
throw new ShutdownException(e);
}
logger.info("{}-{} - GPIO BCM is closed. Recreate the pin object to reuse.", line.deviceName, line.mask);
return this;
super.close();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,12 @@ private int internalWrite(byte[] data, int offset, int length) {
* I2C bus file descriptor.
*/
@Override
public I2C shutdownInternal(Context context) {
super.shutdownInternal(context);
public void close() {
if (closed) {
return;
}
i2CBus.close();
return this;
super.close();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import com.pi4j.context.Context;
import com.pi4j.exception.InitializeException;
import com.pi4j.exception.Pi4JException;
import com.pi4j.exception.ShutdownException;
import com.pi4j.io.i2c.I2C;
import com.pi4j.io.i2c.I2CBase;
import com.pi4j.io.i2c.I2CConfig;
Expand Down Expand Up @@ -181,10 +180,12 @@ public int writeRegister(byte[] register, byte[] data, int offset, int length) {
}

@Override
public I2C shutdownInternal(Context context) throws ShutdownException {
super.shutdownInternal(context);
public void close() {
if (closed) {
return;
}
i2CBus.close();
return this;
super.close();
}

@Override
Expand Down
Loading
Loading