1 package kaka.cakelight;
4 import java.util.Optional;
5 import java.util.function.Consumer;
7 import static kaka.cakelight.Main.log;
9 public class VideoDeviceListener {
10 private Thread thread;
11 private Consumer<Optional<File>> changeConsumer;
12 private File lastDevice = null;
14 public void startListening() {
15 thread = new Thread() {
18 while (!isInterrupted()) {
19 Optional<File> device = findVideoDevice();
20 if (!device.equals(Optional.ofNullable(lastDevice))) {
21 log("Video device change: %s", device.map(File::getAbsolutePath).orElse("none"));
22 changeConsumer.accept(device);
23 lastDevice = device.orElse(null);
27 } catch (InterruptedException e) {
34 public void stopListening() {
38 private Optional<File> findVideoDevice() {
39 File[] files = new File("/dev").listFiles((dir, name) -> name.matches("video[0-9]+"));
40 if (files == null || files.length == 0) {
41 return Optional.empty();
43 return Optional.of(files[0]);
47 public void onVideoDeviceChange(Consumer<Optional<File>> consumer) {
48 changeConsumer = consumer;