-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigurationView.java
More file actions
519 lines (447 loc) · 17.9 KB
/
ConfigurationView.java
File metadata and controls
519 lines (447 loc) · 17.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
package de.doubleslash.usb_led_matrix.view;
import de.doubleslash.usb_led_matrix.CommandLineOptions;
import de.doubleslash.usb_led_matrix.graph.Graph;
import de.doubleslash.usb_led_matrix.model.Model;
import de.doubleslash.usb_led_matrix.resources.Resources;
import de.doubleslash.usb_led_matrix.usb_adapter.UsbAdapter;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Slider;
import javafx.scene.control.ToggleGroup;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.stage.Stage;
import jssc.SerialPortException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class ConfigurationView {
private static final int POLLING_INTERVALL_SECONDS = 10;
private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
LocalTime timeLightsTurnedOffNow = LocalTime.now();
private final Graph graph = new Graph();
private final Stage popUpStage = new Stage();
private final ToggleGroup radioButtonGroup = new ToggleGroup();
private UsbAdapter usbAdapter;
private Model model;
private Scene scene;
private Thread currentlyRunningThread;
private Thread healthCheckThread;
private boolean startAfterAuthentification;
private boolean timedOut = false;
final Image image = new Image("/images/DsIcon.png");
@FXML
RadioButton manualRadioButton;
@FXML
RadioButton teamsRadioButton;
@FXML
ChoiceBox<String> portChoiceBox;
@FXML
private ColorPicker colorPicker;
@FXML
private Button setColorButton;
@FXML
private Label connectionStatusLabel;
@FXML
private Slider brightnessSlider;
private final Runnable manualModeConnectionCheckRunnable = () -> {
LOG.info("Manual mode started.");
while (true) {
try {
Thread.sleep(POLLING_INTERVALL_SECONDS * 1000);
} catch (final InterruptedException e) {
LOG.debug("Manual mode was interrupted.", e);
return;
}
}
};
private final Runnable teamsPollingRunnable = () -> {
LOG.info("MS Teams status polling started.");
while (true) {
try {
try {
model.setColor(graph.getStatusColorFromTeams());
} catch (final IOException ioe) {
LOG.error("Microsoft server connection lost.", ioe);
}
Thread.sleep(POLLING_INTERVALL_SECONDS * 1000);
} catch (final InterruptedException ie) {
LOG.debug("MS Teams status polling was interrupted.", ie);
return;
}
}
};
private final Runnable healthCheckRunnable = () -> {
while (true) {
try {
model.setCheckConnection(false);
usbAdapter.connectionCheck();
Thread.sleep(POLLING_INTERVALL_SECONDS * 1000);
} catch (final InterruptedException e) {
LOG.debug("Connection check was interrupted.", e);
return;
}
turnOffAutomaticallyIfNeeded(LocalTime.now());
}
};
private final Runnable reconnectionCheckRunnable = () -> {
while (true) {
try {
reconnect();
Thread.sleep(POLLING_INTERVALL_SECONDS * 1000);
} catch (final InterruptedException e) {
LOG.debug("Reconnection check was interrupted.", e);
return;
}
turnOffAutomaticallyIfNeeded(LocalTime.now());
}
};
private final Task<Void> deviceCodePollingTask = new Task<>() {
@Override
protected Void call() {
String answerBody = "authorization_pending";
LOG.info("Start polling for token.");
updateMessage("Polling for Token...");
while (answerBody.contains("authorization_pending")) {
try {
answerBody = graph.pollingForToken(model.getDeviceCode());
LOG.debug("Polling for token. Answer was: '{}'.", answerBody);
Thread.sleep(POLLING_INTERVALL_SECONDS * 500);
} catch (IOException | InterruptedException e) {
LOG.error("Could not get answer from server.", e);
}
}
if (answerBody.contains("access_token")) {
LOG.info("Received token");
updateMessage("Received token");
try {
graph.extractAndStoreAccessRefreshToken(answerBody);
} catch (final IOException e) {
LOG.error("Could not get access and refresh token", e);
}
LOG.info("Token was successfully saved");
startNamedThreadWithRunnable(teamsPollingRunnable, "Teams");
}
return null;
}
};
@FXML
private void initialize() {
LOG.debug("Initialize configuration view.");
popUpStage.initModality(Modality.WINDOW_MODAL);
connectionStatusLabel.setTextFill(Color.BLACK);
teamsRadioButton.setToggleGroup(radioButtonGroup);
manualRadioButton.setToggleGroup(radioButtonGroup);
radioButtonGroup.selectedToggleProperty().addListener((observable, oldValue, newValue) -> {
LOG.trace("newValue is '{}'.", newValue);
model.setSelectedToggle(newValue);
if (newValue == manualRadioButton) {
manualMode();
return;
}
LOG.info("Teams mode activated");
final boolean isRefreshTokenAvailable = graph.isRefreshTokenAvailable();
model.setLoggedIntoTeams(isRefreshTokenAvailable);
if (isRefreshTokenAvailable) {
LOG.info("Refresh token available");
teamsMode();
}
if (!model.isLoggedIntoTeams()) {
LOG.info("Start Device Code Flow.");
final Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setContentText("You need to log in.");
final Optional<ButtonType> optionalButtonType = alert.showAndWait();
if (optionalButtonType.isPresent()) {
final ButtonType buttonType = optionalButtonType.get();
if (buttonType.equals(ButtonType.CANCEL)) {
Platform.runLater(() -> radioButtonGroup.selectToggle(manualRadioButton));
} else {
final FXMLLoader fxmlLoader = new FXMLLoader(Resources.AUTHENTICATION_VIEW.getResource());
try {
final Parent root = fxmlLoader.load();
final AuthenticationView authFlow = fxmlLoader.getController();
final Scene scene = new Scene(root);
authFlow.setScene(scene);
authFlow.customInitialize();
model.deviceCodeProperty().bind(authFlow.getDeviceCodeProperty());
deviceCodePollingTask.setOnFailed(
(event -> LOG.info("Polling task failed '{}'.", event, event.getSource().getException())));
deviceCodePollingTask.setOnSucceeded((event -> {
LOG.info("Polling task succeeded.");
popUpStage.close();
}));
new Thread(deviceCodePollingTask).start();
authFlow.pollingMessage.textProperty().bind(deviceCodePollingTask.messageProperty());
authFlow.pollingMessage.setTextFill(Color.web("#58c443"));
popUpStage.setResizable(false);
popUpStage.setScene(scene);
popUpStage.getIcons().add(image);
popUpStage.setTitle("Authentication");
popUpStage.showAndWait();
startAfterAuthentification = true;
} catch (IOException e) {
LOG.error("Could not load view '{}'", Resources.AUTHENTICATION_VIEW, e);
}
}
}
}
if (startAfterAuthentification && model.connectedProperty().getValue()) {
brightnessSlider.setDisable(false);
connectionStatusLabel.setText("Connected to device.");
connectionStatusLabel.setTextFill(Color.GREEN);
model.setColor(Color.BLACK);
usbAdapter.updatePixel(model.brightnessProperty().getValue());
}
});
initializeSetColorButton();
initializeBrightness();
}
private void manualMode() {
LOG.info("Manual mode activated");
if (model.connectedProperty().getValue()) {
colorPicker.setDisable(false);
setColorButton.setDisable(false);
brightnessSlider.setDisable(false);
model.setColor(colorPicker.getValue());
model.setBrightnessFromPercentage(brightnessSlider.getValue());
usbAdapter.updatePixel(model.colorProperty().getValue(), model.brightnessProperty().getValue());
startNamedThreadWithRunnable(manualModeConnectionCheckRunnable, "Manual");
}
}
private void teamsMode() {
LOG.info("teams mode activated");
if (model.connectedProperty().getValue()) {
startNamedThreadWithRunnable(teamsPollingRunnable, "Teams");
colorPicker.setDisable(true);
setColorButton.setDisable(true);
}
}
private void initializeSetColorButton() {
LOG.debug("Initialize setColorButton.");
setColorButton.setOnAction(actionEvent -> model.setColor(colorPicker.getValue()));
}
void initializePortChoiceBox() {
LOG.debug("Initialize portChoiceBox.");
portChoiceBox.valueProperty().addListener((observable, oldValue, newValue) -> {
LOG.debug("Port changed from '{}' to '{}'", oldValue, newValue);
if (newValue != null) {
model.setPortName(newValue);
}
});
selectPortComboBoxItem(CommandLineOptions.getCom());
}
private void selectPortComboBoxItem(final String portName) {
final List<String> validPortNames = new ArrayList<>(model.getSerialPorts());
if (validPortNames.contains(portName)) {
LOG.warn("Changing port to '{}'.", portName);
portChoiceBox.getSelectionModel().select(portName);
} else {
LOG.error("The port name '{}' is invalid.", portName);
}
}
private void initializeBrightness() {
LOG.debug("Initialize Brightness.");
brightnessSlider.setOnMouseReleased(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent event) {
model.setBrightnessFromPercentage(brightnessSlider.getValue());
LOG.debug("Brightness changed to '{}'", brightnessSlider.getValue());
}
});
}
public void setModel(final Model model) {
this.model = model;
}
public void setScene(final Scene scene) {
this.scene = scene;
}
public void dataInitialization(final UsbAdapter usbAdapter) {
LOG.debug("Initialize data of configuration view.");
model.colorProperty().addListener((observable, oldValue, newValue) -> {
timeLightsTurnedOffNow = LocalTime.now();
timedOut = false;
});
this.usbAdapter = usbAdapter;
if (CommandLineOptions.getColorMode().equals("light")) {
CommandLineOptions.Light(scene);
} else if (CommandLineOptions.getColorMode().equals("dark")) {
CommandLineOptions.Dark(scene);
}
portChoiceBox.setItems(model.getSerialPorts());
initializePortChoiceBox();
if (CommandLineOptions.getMode().equals("manual")) {
radioButtonGroup.selectToggle(manualRadioButton);
} else if (CommandLineOptions.getMode().equals("teams")) {
radioButtonGroup.selectToggle(teamsRadioButton);
}
if (model.getSelectedToggle() == null) {
LOG.trace("model.getSelectedToggle is '{}'.", model.getSelectedToggle());
radioButtonGroup.selectToggle(manualRadioButton);
} else {
radioButtonGroup.selectToggle(model.getSelectedToggle());
}
model.setBrightnessFromPercentage(CommandLineOptions.getBrightness());
brightnessSlider.setValue(CommandLineOptions.getBrightness());
registerConnectedListener();
healthCheckThread = new Thread(healthCheckRunnable);
healthCheckThread.setName("Health");
healthCheckThread.start();
}
private void registerConnectedListener() {
LOG.debug("Initialize connectedProperty.");
model.connectedProperty().addListener((observable, oldValue, newValue) -> {
LOG.debug("connectedProperty changed from '{}' to '{}'.", oldValue, newValue);
if (newValue == Boolean.TRUE) {
handleSuccess();
}
if (newValue == Boolean.FALSE) {
handleFailure();
}
});
}
private void handleSuccess() {
LOG.debug("Setting connectionStatusLabel to success.");
if (manualRadioButton.isSelected()) {
colorPicker.setDisable(false);
setColorButton.setDisable(false);
}
brightnessSlider.setDisable(false);
connectionStatusLabel.setText("Connected to device.");
if (manualRadioButton.isSelected()) {
startNamedThreadWithRunnable(manualModeConnectionCheckRunnable, "Manual");
} else {
startNamedThreadWithRunnable(teamsPollingRunnable, "Teams");
}
model.setColor(Color.BLACK);
if (usbAdapter.connectionBoolean == true) {
setColorButton.fire();
usbAdapter.connectionBoolean = false;
}
usbAdapter.updatePixel(model.colorProperty().getValue(), model.brightnessProperty().getValue());
connectionStatusLabel.setTextFill(Color.GREEN);
refreshButton();
}
private void handleFailure() {
LOG.debug("Setting connectionStatusLabel to failure.");
connectionStatusLabel.setTextFill(Color.RED);
connectionStatusLabel.setText("Not connected to device.");
currentlyRunningThread.interrupt();
usbAdapter.closePort();
startNamedThreadWithRunnable(reconnectionCheckRunnable, "reconnectionThread");
}
Co2View co2View;
private void startNamedThreadWithRunnable(final Runnable runnable, final String name) {
if (currentlyRunningThread != null && currentlyRunningThread.isAlive()) {
currentlyRunningThread.interrupt();
}
currentlyRunningThread = new Thread(runnable);
currentlyRunningThread.setName(name);
currentlyRunningThread.start();
}
void reconnect() {
usbAdapter.connect();
model.setColor(Color.BLACK);
}
@FXML
void refreshButton() {
final String currentPort = model.getPortName();
model.getSerialPorts().setAll(UsbAdapter.getSerialPortNames());
if (model.getSerialPorts().contains(currentPort)) {
selectPortComboBoxItem(currentPort);
} else if (model.getSerialPorts().contains(CommandLineOptions.getCom())) {
selectPortComboBoxItem(CommandLineOptions.getCom());
}
}
void turnOffAutomaticallyIfNeeded(final LocalTime currentTime) {
final LocalTime timeLightsTurnedOff = timeLightsTurnedOffNow.plusMinutes(CommandLineOptions.getTimeout());
if (!currentTime.isBefore(timeLightsTurnedOff) && !timedOut) {
LOG.info("Turn off automatically at '{}'", timeLightsTurnedOff);
usbAdapter.updatePixel(Color.BLACK);
timedOut = true;
}
}
void setUsbAdapter(final UsbAdapter usbAdapter) {
this.usbAdapter = usbAdapter;
}
@FXML
void toggleLightMode(final MouseEvent event) {
CommandLineOptions.Light(scene);
}
@FXML
void toggleDarkMode(final MouseEvent event) {
CommandLineOptions.Dark(scene);
}
@FXML
void showInfoView() {
final FXMLLoader fxmlLoader = new FXMLLoader(Resources.INFO_VIEW.getResource());
try {
Stage stage = new Stage();
usbAdapter.requestVersion();
final Parent root = fxmlLoader.load();
final VersionView versionView = fxmlLoader.getController();
final Scene scene = new Scene(root);
versionView.setScene(scene);
versionView.instantiate(usbAdapter.versionProperty());
stage.setScene(scene);
stage.getIcons().add(image);
stage.setTitle("Info");
stage.setResizable(false);
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
} catch (final IOException | SerialPortException e) {
LOG.error("Could not load view '{}'.", Resources.INFO_VIEW, e);
}
}
@FXML
void showCo2View() {
final FXMLLoader fxmlLoader = new FXMLLoader(Resources.CO2_VIEW.getResource());
try {
Stage stage = new Stage();
final Parent root = fxmlLoader.load();
final Scene scene = new Scene(root);
stage.setTitle("Co2 Sensordaten");
stage.setScene(scene);
stage.setResizable(false);
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
} catch (final IOException e) {
LOG.error("Could not load view '{}'.", Resources.CO2_VIEW, e);
}
}
@FXML
void showSettingsView() {
final FXMLLoader fxmlLoader = new FXMLLoader(Resources.SETTINGS_VIEW.getResource());
try {
Stage stage = new Stage();
final Parent root = fxmlLoader.load();
final Scene scene = new Scene(root);
stage.setTitle("Settings");
stage.setScene(scene);
stage.setResizable(false);
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
} catch (final IOException e) {
LOG.error("Could not load view '{}'.", Resources.SETTINGS_VIEW, e);
}
}
}