Skip to content

Commit

Permalink
🚧 #70 some fixes, update fallback service test
Browse files Browse the repository at this point in the history
  • Loading branch information
rucko24 committed Oct 31, 2024
1 parent 7e54554 commit ed6bb97
Show file tree
Hide file tree
Showing 10 changed files with 242 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
* </ul>
*
* <p>
* Para FreeBSD se debe instalar el <strong>esptool.py desde los ports </strong>
* For FreeBSD you must install the <strong>esptool.py from the <strong>ports</strong>.
* </p>
*
*
Expand Down Expand Up @@ -71,7 +71,7 @@ public CommandLineRunner moveEsptoolBundleToTempDir() {
/**
* Moves the executable from the resources directory to the temporary directory
*
* @param bundleFileName the name of the executable, depending on the operating systemº
* @param bundleFileName the name of the executable, depending on the operating system
*/
private void moveBundleToTempDirectory(final String bundleFileName) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
* @author rubn
*/
@Service
public class EspDeviceInfoFallBackService {
public class EsptoolFallBackService {

/**
*
Expand All @@ -35,7 +35,7 @@ public Mono<EspDeviceInfo> fallback(String parsedPort) {
*
* @return A {@link Mono}
*/
public Mono<String> portListingIsEmpty() {
public Mono<String> fallbackEmptyPorts() {
return Mono.error(new CanNotBeReadDeviceException("Possibly empty ports"));
}
}
23 changes: 7 additions & 16 deletions src/main/java/com/esp/espflow/service/EsptoolService.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.esp.espflow.entity.EspDeviceInfo;
import com.esp.espflow.enums.BaudRates;
import com.esp.espflow.exceptions.CanNotBeReadDeviceException;
import com.esp.espflow.mappers.EspDeviceInfoMapper;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
Expand Down Expand Up @@ -41,7 +40,7 @@ public class EsptoolService {

private final CommandService commandService;
private final ComPortService comPortService;
private final EspDeviceInfoFallBackService espDeviceInfoFallBackService;
private final EsptoolFallBackService esptoolFallBackService;
private final EsptoolPathService esptoolPathService;

/**
Expand All @@ -60,20 +59,11 @@ public class EsptoolService {
*/
public Flux<EspDeviceInfo> readAllDevices() {
return Flux.fromIterable(comPortService.getPortsListWithFriendlyName())
.switchIfEmpty(this.portListingIsEmpty())
.switchIfEmpty(Mono.defer(this.esptoolFallBackService::fallbackEmptyPorts))
.flatMap(this::readFlashIdFromPort)
.doOnNext(onNext -> log.info("onNext device: {}", onNext));
}

/**
* This allows us to raise the exception type {@link CanNotBeReadDeviceException}, when the port list is empty.
*
* @return A {@link Mono}
*/
private Mono<String> portListingIsEmpty() {
return Mono.defer(() -> Mono.error(new CanNotBeReadDeviceException("Possibly empty ports")));
}

/**
* <p>Counting of all ports filtering out those of</p>
*
Expand Down Expand Up @@ -122,7 +112,7 @@ public Mono<EspDeviceInfo> readFlashIdFromPort(String port) {
.flatMap(collectedMapInfo -> EspDeviceInfoMapper.INSTANCE.mapToEspDeviceInfo(
collectedMapInfo, descriptivePortName)
)
.switchIfEmpty(Mono.defer(() -> this.espDeviceInfoFallBackService.fallback(parsedPort)));
.switchIfEmpty(Mono.defer(() -> this.esptoolFallBackService.fallback(parsedPort)));
}

/**
Expand Down Expand Up @@ -181,7 +171,8 @@ private String processLineEsptoolVersion(final String rawLine) {
*
* <blockquote><pre>
* esptool.py --port /dev/ttyUSB1 --baud customBaudRate read_flash 0 ALL esp8266-backupflash.bin
* </pre></blockquote><p>
* </pre>
* </blockquote><p>
*
* @param commands the commands to process
* @return A {@link Flux<String>}
Expand Down Expand Up @@ -223,13 +214,13 @@ private String splitPercentaje(String input) {
/**
* Create the folder named <strong>/esp-backup-flash-dir</strong> in the temporary directory of the operating system
*/
public void createEspBackUpFlashDirIfNotExists() {
public void createEspBackUpFlashDirIfNotExists() throws IOException {
final Path espBackupFlashDir = Path.of(JAVA_IO_TEMPORAL_DIR_OS.concat("/esp-backup-flash-dir"));
if (!Files.exists(espBackupFlashDir)) {
try {
Files.createDirectory(espBackupFlashDir);
} catch (IOException e) {
log.debug("Error creating directory /esp-backup-flash-dir {}", e.getMessage());
throw new IOException("Error creating directory /esp-backup-flash-dir on " + e.getMessage());
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,17 +221,17 @@ public WriteFlashBuilder make() {
};

final String[] commands = Arrays.stream(preCommands)
.filter(item -> !item.isEmpty()) //remove empty Strings
.filter(item -> item != null && !item.isEmpty()) //remove empty Strings
.toArray(String[]::new);

final List<String> errorFields = new CopyOnWriteArrayList<>();

if(serialPort.getValue() == null){
errorFields.add("Serial port is null");
errorFields.add("Serial port is empty");
}

if(flashFileName == null) {
errorFields.add("flashFileName port is null");
errorFields.add("Firmware does not exist");
}

if(errorFields.isEmpty()) {
Expand Down
22 changes: 22 additions & 0 deletions src/main/java/com/esp/espflow/views/readflash/ReadFlashView.java
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ private Div rigthFormForAddress() {
autoDetectFlashSize.setSizeUndefined();
autoDetectFlashSize.addValueChangeListener(event -> {
if (event.getValue()) {
endAddress.setValue(0);
endAddress.setEnabled(false);
} else {
endAddress.setEnabled(true);
Expand Down Expand Up @@ -330,6 +331,7 @@ private void showDetectedDevices(final UI ui, final EspDevicesCarousel paramEspD
this.esptoolService.readAllDevices()
.flatMap(this.countAllDevices())
.flatMap(this.configureSlides(ui, paramEspDevicesCarousel, spansList))
.doOnError(canNotBeReadDevice -> this.onError(ui, canNotBeReadDevice))
.doOnComplete(() -> this.onComplete(ui, paramEspDevicesCarousel, spansList))
.subscribe(resultEspDevicesCarousel -> {
ui.access(() -> {
Expand Down Expand Up @@ -474,6 +476,26 @@ private Mono<EspDevicesCarousel> configureSlides(final Set<Span> spansList,

}

/**
*
* En caso de no poder leer ningun puerto serie, es decir el dispositivo no esta conectado, se deberia
* revisar la conexion con el puerto USB
*
* <p>new CanNotBeReadDeviceException("Possibly empty ports")</`p>
*
* @param ui the UI
* @param canNotBeReadDevice Possibly empty ports
*/
private void onError(final UI ui, Throwable canNotBeReadDevice) {
ui.access(() -> {
//En caso que desde Java no logremos leer ningun puerto /dev/tty* /dev/cua*
ConfirmDialogBuilder.showWarning(canNotBeReadDevice.getMessage());
this.setDivCarouselNoDevicesShown();
this.leftPrimarySectionProgressBar.setVisible(false);
this.buttonRefreshDevices.setEnabled(true);
});
}

/**
* <p>This piece of code is executed when the reactive stream is completed.</p>
* <p>In case the Slides are empty, we display the initial text in the DIV "No devices shown!"; </p>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import lombok.Getter;
import lombok.extern.log4j.Log4j2;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Objects;
Expand Down Expand Up @@ -407,9 +408,8 @@ private Button buttonForReadFlash(final UI ui, final FlashButtonWrapperService f
|| text.toString().isEmpty(), "Invalid input, set only numbers")
.bind(AddressRecordBinder::startAddressSize, (addressRecordBinder, value) -> {});
addressRecordBinderBinder.forField(customSizeToRead)
.withValidator(text -> text.toString().matches("^[1-9]\\d*$\n")
|| text.toString().isEmpty()
|| text != 0, "Invalid input, set only numbers and greater than zero")
.withValidator(text -> text.toString().matches("\\d+"),
"Invalid input, set only numbers and greater than zero")
.bind(AddressRecordBinder::customAddresSize, (addressRecordBinder, value) -> {});

downloadFlashButton.addClickListener(event -> {
Expand All @@ -431,16 +431,16 @@ private Button buttonForReadFlash(final UI ui, final FlashButtonWrapperService f
*/
private void validate(final FlashButtonWrapperService flashButtonWrapperService) {
String processAutoDetectFlashSize = "";
if (autoDetectFlashSize.getValue()) {
if (Boolean.TRUE.equals(autoDetectFlashSize.getValue())) {
processAutoDetectFlashSize = "ALL";
readFlash(flashButtonWrapperService, processAutoDetectFlashSize);
this.readFlash(flashButtonWrapperService, processAutoDetectFlashSize);
} else {
if(!customSizeToRead.isEmpty()) {
if(customSizeToRead.getValue() != 0) {
processAutoDetectFlashSize = "0x".concat(String.valueOf(customSizeToRead.getValue()));
readFlash(flashButtonWrapperService, processAutoDetectFlashSize);
this.readFlash(flashButtonWrapperService, processAutoDetectFlashSize);
} else {
ConfirmDialogBuilder.showWarning("Please set the custom size or enable the button for full readability.");
customSizeToRead.focus();
ConfirmDialogBuilder.showWarning("Please set the custom size greater than zero, or enable the button for full readability.");
}

}
Expand All @@ -452,7 +452,11 @@ private void validate(final FlashButtonWrapperService flashButtonWrapperService)
* @param processAutoDetectFlashSize
*/
private void readFlash(final FlashButtonWrapperService flashButtonWrapperService, String processAutoDetectFlashSize) {
esptoolService.createEspBackUpFlashDirIfNotExists();
try {
esptoolService.createEspBackUpFlashDirIfNotExists();
} catch (IOException e) {
throw new RuntimeException(e);
}
final String currentTimeMillis = String.valueOf(System.currentTimeMillis());
final String fileNameResult = espDeviceInfo.chipIs().concat("-")
.concat(currentTimeMillis).concat("-backup.bin");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.esp.espflow.service;

import com.esp.espflow.entity.EspDeviceInfo;
import com.esp.espflow.exceptions.CanNotBeReadDeviceException;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
Expand All @@ -17,6 +19,7 @@ class EsptoolFallBackServiceTest {
private EsptoolFallBackService service;

@Test
@DisplayName("An EspDeviceInfo is returned with the port only, no exception is returned.")
void fallback() {

var espDeviceInfo = EspDeviceInfo.builder()
Expand All @@ -28,4 +31,21 @@ void fallback() {
.verifyComplete();

}

@Test
@DisplayName("When the service returns an empty Set, because there are no available ports, this is not the case when the ports do not have read permissions.")
void fallbackEmptyPorts() {

StepVerifier.create(this.service.fallbackEmptyPorts())
.expectError(CanNotBeReadDeviceException.class)
.verify();

StepVerifier.create(this.service.fallbackEmptyPorts())
.expectErrorMatches(error -> error.getMessage().contains("Possibly empty ports"))
.verify();

}



}
Loading

0 comments on commit ed6bb97

Please sign in to comment.