| 1 | package kaka.cakelight; |
| 2 | |
| 3 | import java.io.File; |
| 4 | import java.util.Optional; |
| 5 | import java.util.function.Consumer; |
| 6 | |
| 7 | import static kaka.cakelight.Main.log; |
| 8 | |
| 9 | public class VideoDeviceListener { |
| 10 | private Thread thread; |
| 11 | private Consumer<Optional<File>> changeConsumer; |
| 12 | private File lastDevice = null; |
| 13 | |
| 14 | public void startListening() { |
| 15 | thread = new Thread() { |
| 16 | public void run() { |
| 17 | try { |
| 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); |
| 24 | } |
| 25 | Thread.sleep(1000); |
| 26 | } |
| 27 | } catch (InterruptedException e) { |
| 28 | } |
| 29 | } |
| 30 | }; |
| 31 | thread.start(); |
| 32 | } |
| 33 | |
| 34 | public void stopListening() { |
| 35 | thread.interrupt(); |
| 36 | } |
| 37 | |
| 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(); |
| 42 | } else { |
| 43 | return Optional.of(files[0]); |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | public void onVideoDeviceChange(Consumer<Optional<File>> consumer) { |
| 48 | changeConsumer = consumer; |
| 49 | } |
| 50 | } |