Skip to content

Commit

Permalink
Made sure that GpioDDigitalInput is completely shut down after shutdown.
Browse files Browse the repository at this point in the history
  • Loading branch information
alex9849 committed Feb 9, 2024
1 parent fca06c8 commit 51e243d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
* <p>PiGpioDigitalOutput class.</p>
Expand Down Expand Up @@ -69,19 +70,24 @@ public DigitalInput initialize(Context context) throws InitializeException {
@Override
public void run() {
DigitalState lastState = null;
while (true) {
while (!Thread.interrupted()) {
long debounceNs = GpioDDigitalInput.this.debounceNs;
// We have to use this function before calling eventRead() directly, since native methods can't be interrupted.
// eventRead() is blocking and prevents thread interrupt while running
while (!GpioDDigitalInput.this.line.eventWait(inputMaxWaitNs)) {
continue;
if (Thread.interrupted()) {
return;
}
}
GpioLineEvent lastEvent = GpioDDigitalInput.this.line.eventRead();
long currentTime = System.nanoTime();

// Perform debouncing
// If the event is too new to be sure that it is debounced then ...
while (lastEvent.getTimeNs() + debounceNs >= currentTime) {
if (Thread.interrupted()) {
return;
}
// ... wait for remaining debounce time and watch out for new event(s)
if(GpioDDigitalInput.this.line.eventWait(Math.min(inputMaxWaitNs, lastEvent.getTimeNs() + debounceNs - currentTime))) {
// Repeat if a second event occurred withing debounce interval
Expand All @@ -97,7 +103,6 @@ public void run() {
lastState = newState;
GpioDDigitalInput.this.dispatch(new DigitalStateChangeEvent(GpioDDigitalInput.this, newState));
}

}
}
};
Expand All @@ -108,9 +113,14 @@ public void run() {

@Override
public DigitalInput shutdown(Context context) throws ShutdownException {
super.shutdown(context);
executor.shutdown();
this.line.release();
try {
super.shutdown(context);
executor.shutdownNow();
executor.awaitTermination(5, TimeUnit.SECONDS);
this.line.release();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ public DigitalOutput initialize(Context context) throws InitializeException {

@Override
public DigitalOutput shutdown(Context context) throws ShutdownException {
DigitalOutput returnMe = super.shutdown(context);
super.shutdown(context);
this.line.release();
return returnMe;
return this;
}

/**
Expand Down

0 comments on commit 51e243d

Please sign in to comment.