diff --git a/tools/cooja/java/org/contikios/cooja/contikimote/ContikiMoteType.java b/tools/cooja/java/org/contikios/cooja/contikimote/ContikiMoteType.java index 6d58d2d6a..6ad0b9da5 100644 --- a/tools/cooja/java/org/contikios/cooja/contikimote/ContikiMoteType.java +++ b/tools/cooja/java/org/contikios/cooja/contikimote/ContikiMoteType.java @@ -27,7 +27,6 @@ * SUCH DAMAGE. * */ - package org.contikios.cooja.contikimote; import java.awt.Container; @@ -41,6 +40,7 @@ import java.lang.reflect.Method; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Random; @@ -93,7 +93,8 @@ import org.contikios.cooja.util.StringUtils; @ClassDescription("Cooja mote") @AbstractionLevelDescription("OS level") public class ContikiMoteType implements MoteType { - private static Logger logger = Logger.getLogger(ContikiMoteType.class); + + private static final Logger logger = Logger.getLogger(ContikiMoteType.class); public static final String ID_PREFIX = "mtype"; @@ -121,6 +122,7 @@ public class ContikiMoteType implements MoteType { * Communication stacks in Contiki. */ public enum NetworkStack { + DEFAULT, MANUAL; public String manualHeader = "netstack-conf-example.h"; @@ -167,7 +169,7 @@ public class ContikiMoteType implements MoteType { } } - private final String[] sensors = { "button_sensor", "pir_sensor", "vib_sensor" }; + private final String[] sensors = {"button_sensor", "pir_sensor", "vib_sensor"}; private String identifier = null; private String description = null; @@ -177,10 +179,15 @@ public class ContikiMoteType implements MoteType { /* For internal use only: using during Contiki compilation. */ private File contikiApp = null; /* Contiki application: hello-world.c */ + public File libSource = null; /* JNI library: obj_cooja/mtype1.c */ + public File libFile = null; /* JNI library: obj_cooja/mtype1.lib */ + public File archiveFile = null; /* Contiki archive: obj_cooja/mtype1.a */ + public File mapFile = null; /* Contiki map: obj_cooja/mtype1.map */ + public String javaClassName = null; /* Loading Java class name: Lib1 */ private String[] coreInterfaces = null; @@ -213,18 +220,18 @@ public class ContikiMoteType implements MoteType { @Override public boolean configureAndInit(Container parentContainer, Simulation simulation, - boolean visAvailable) throws MoteTypeCreationException { + boolean visAvailable) throws MoteTypeCreationException { myConfig = simulation.getCooja().getProjectConfig().clone(); if (visAvailable) { if (getDescription() == null) { - setDescription("Cooja Mote Type #" + (simulation.getMoteTypes().length+1)); + setDescription("Cooja Mote Type #" + (simulation.getMoteTypes().length + 1)); } /* Compile Contiki from dialog */ - boolean compileOK = - ContikiMoteCompileDialog.showDialog(parentContainer, simulation, this); + boolean compileOK + = ContikiMoteCompileDialog.showDialog(parentContainer, simulation, this); if (!compileOK) { return false; } @@ -240,17 +247,17 @@ public class ContikiMoteType implements MoteType { /* Create variables used for compiling Contiki */ contikiApp = getContikiSourceFile(); libSource = new File( - contikiApp.getParentFile(), - "obj_cooja/" + getIdentifier() + ".c"); + contikiApp.getParentFile(), + "obj_cooja/" + getIdentifier() + ".c"); libFile = new File( - contikiApp.getParentFile(), - "obj_cooja/" + getIdentifier() + librarySuffix); + contikiApp.getParentFile(), + "obj_cooja/" + getIdentifier() + librarySuffix); archiveFile = new File( - contikiApp.getParentFile(), - "obj_cooja/" + getIdentifier() + dependSuffix); + contikiApp.getParentFile(), + "obj_cooja/" + getIdentifier() + dependSuffix); mapFile = new File( - contikiApp.getParentFile(), - "obj_cooja/" + getIdentifier() + mapSuffix); + contikiApp.getParentFile(), + "obj_cooja/" + getIdentifier() + mapSuffix); javaClassName = CoreComm.getAvailableClassName(); if (javaClassName == null) { @@ -265,37 +272,36 @@ public class ContikiMoteType implements MoteType { /* Generate Contiki main source */ /*try { - CompileContiki.generateSourceFile( - libSource, - javaClassName, - getSensors(), - getCoreInterfaces() - ); - } catch (Exception e) { - throw (MoteTypeCreationException) new MoteTypeCreationException( - "Error when generating Contiki main source").initCause(e); - }*/ + CompileContiki.generateSourceFile( + libSource, + javaClassName, + getSensors(), + getCoreInterfaces() + ); + } catch (Exception e) { + throw (MoteTypeCreationException) new MoteTypeCreationException( + "Error when generating Contiki main source").initCause(e); + }*/ /* Prepare compiler environment */ String[][] env; try { env = CompileContiki.createCompilationEnvironment( - getIdentifier(), - contikiApp, - mapFile, - libFile, - archiveFile, - javaClassName); + getIdentifier(), + contikiApp, + mapFile, + libFile, + archiveFile, + javaClassName); CompileContiki.redefineCOOJASources( - this, - env + this, + env ); } catch (Exception e) { - throw (MoteTypeCreationException) new MoteTypeCreationException( - "Error when creating environment: " + e.getMessage()).initCause(e); + throw new MoteTypeCreationException("Error when creating environment: " + e.getMessage(), e); } String[] envOneDimension = new String[env.length]; - for (int i=0; i < env.length; i++) { + for (int i = 0; i < env.length; i++) { envOneDimension[i] = env[i][0] + "=" + env[i][1]; } @@ -305,31 +311,31 @@ public class ContikiMoteType implements MoteType { } final MessageList compilationOutput = new MessageList(); String[] arr = getCompileCommands().split("\n"); - for (String cmd: arr) { + for (String cmd : arr) { if (cmd.trim().isEmpty()) { continue; } try { CompileContiki.compile( - cmd, - envOneDimension, - null /* Do not observe output firmware file */, - getContikiSourceFile().getParentFile(), - null, - null, - compilationOutput, - true + cmd, + envOneDimension, + null /* Do not observe output firmware file */, + getContikiSourceFile().getParentFile(), + null, + null, + compilationOutput, + true ); } catch (Exception e) { - MoteTypeCreationException newException = - new MoteTypeCreationException("Mote type creation failed: " + e.getMessage()); + MoteTypeCreationException newException + = new MoteTypeCreationException("Mote type creation failed: " + e.getMessage()); newException = (MoteTypeCreationException) newException.initCause(e); newException.setCompilationOutput(compilationOutput); /* Print last 10 compilation errors to console */ MessageContainer[] messages = compilationOutput.getMessages(); - for (int i=messages.length-10; i < messages.length; i++) { + for (int i = messages.length - 10; i < messages.length; i++) { if (i < 0) { continue; } @@ -342,8 +348,8 @@ public class ContikiMoteType implements MoteType { } /* Make sure compiled firmware exists */ - if (getContikiFirmwareFile() == null || - !getContikiFirmwareFile().exists()) { + if (getContikiFirmwareFile() == null + || !getContikiFirmwareFile().exists()) { throw new MoteTypeCreationException("Contiki firmware file does not exist: " + getContikiFirmwareFile()); } } @@ -355,7 +361,7 @@ public class ContikiMoteType implements MoteType { public static File getExpectedFirmwareFile(File source) { File parentDir = source.getParentFile(); - String sourceNoExtension = source.getName().substring(0, source.getName().length()-2); + String sourceNoExtension = source.getName().substring(0, source.getName().length() - 2); return new File(parentDir, sourceNoExtension + librarySuffix); } @@ -363,8 +369,10 @@ public class ContikiMoteType implements MoteType { /** * For internal use. * - * This method creates a core communicator linking a Contiki library and a Java class. - * It furthermore parses library Contiki memory addresses and creates the initial memory. + * This method creates a core communicator linking a Contiki library and a + * Java class. + * It furthermore parses library Contiki memory addresses and creates the + * initial memory. * * @throws MoteTypeCreationException */ @@ -372,11 +380,11 @@ public class ContikiMoteType implements MoteType { if (myCoreComm != null) { throw new MoteTypeCreationException( - "Core communicator already used: " + myCoreComm.getClass().getName()); + "Core communicator already used: " + myCoreComm.getClass().getName()); } - if (getContikiFirmwareFile() == null || - !getContikiFirmwareFile().exists()) { + if (getContikiFirmwareFile() == null + || !getContikiFirmwareFile().exists()) { throw new MoteTypeCreationException("Library file could not be found: " + getContikiFirmwareFile()); } @@ -426,8 +434,8 @@ public class ContikiMoteType implements MoteType { } else { /* Parse command output */ - if (mapFile == null || - !mapFile.exists()) { + if (mapFile == null + || !mapFile.exists()) { throw new MoteTypeCreationException("Map file " + mapFile + " could not be found"); } String[] mapData = loadMapFile(mapFile); @@ -453,38 +461,38 @@ public class ContikiMoteType implements MoteType { } if (dataSectionAddr >= 0) { - logger.info(getContikiFirmwareFile().getName() + - ": data section at 0x" + Integer.toHexString(dataSectionAddr) + - " (" + dataSectionSize + " == 0x" + Integer.toHexString(dataSectionSize) + " bytes)"); + logger.info(getContikiFirmwareFile().getName() + + ": data section at 0x" + Integer.toHexString(dataSectionAddr) + + " (" + dataSectionSize + " == 0x" + Integer.toHexString(dataSectionSize) + " bytes)"); } else { logger.fatal(getContikiFirmwareFile().getName() + ": no data section found"); } if (bssSectionAddr >= 0) { - logger.info(getContikiFirmwareFile().getName() + - ": BSS section at 0x" + Integer.toHexString(bssSectionAddr) + - " (" + bssSectionSize + " == 0x" + Integer.toHexString(bssSectionSize) + " bytes)"); + logger.info(getContikiFirmwareFile().getName() + + ": BSS section at 0x" + Integer.toHexString(bssSectionAddr) + + " (" + bssSectionSize + " == 0x" + Integer.toHexString(bssSectionSize) + " bytes)"); } else { logger.fatal(getContikiFirmwareFile().getName() + ": no BSS section found"); } if (commonSectionAddr >= 0) { - logger.info(getContikiFirmwareFile().getName() + - ": common section at 0x" + Integer.toHexString(commonSectionAddr) + - " (" + commonSectionSize + " == 0x" + Integer.toHexString(commonSectionSize) + " bytes)"); + logger.info(getContikiFirmwareFile().getName() + + ": common section at 0x" + Integer.toHexString(commonSectionAddr) + + " (" + commonSectionSize + " == 0x" + Integer.toHexString(commonSectionSize) + " bytes)"); } else { logger.info(getContikiFirmwareFile().getName() + ": no common section found"); } if (readonlySectionAddr >= 0) { - logger.info(getContikiFirmwareFile().getName() + - ": readonly section at 0x" + Integer.toHexString(readonlySectionAddr) + - " (" + readonlySectionSize + " == 0x" + Integer.toHexString(readonlySectionSize) + " bytes)"); + logger.info(getContikiFirmwareFile().getName() + + ": readonly section at 0x" + Integer.toHexString(readonlySectionAddr) + + " (" + readonlySectionSize + " == 0x" + Integer.toHexString(readonlySectionSize) + " bytes)"); } else { logger.warn(getContikiFirmwareFile().getName() + ": no readonly section found"); } - if (addresses.size() == 0) { + if (addresses.isEmpty()) { throw new MoteTypeCreationException("Library variables parsing failed"); } if (dataSectionAddr <= 0 || dataSectionSize <= 0 - || bssSectionAddr <= 0 || bssSectionSize <= 0) { + || bssSectionAddr <= 0 || bssSectionSize <= 0) { throw new MoteTypeCreationException("Library section addresses parsing failed"); } @@ -493,8 +501,7 @@ public class ContikiMoteType implements MoteType { int referenceVar = addresses.get("referenceVar"); myCoreComm.setReferenceAddress(referenceVar); } catch (Exception e) { - throw (MoteTypeCreationException) new MoteTypeCreationException( - "JNI call error: " + e.getMessage()).initCause(e); + throw new MoteTypeCreationException("JNI call error: " + e.getMessage(), e); } /* We first need the value of Contiki's referenceVar, which tells us the @@ -515,8 +522,8 @@ public class ContikiMoteType implements MoteType { tmp.setMemorySegment(bssSectionAddr, bss); offset = varMem.getIntValueOf("referenceVar"); - logger.info(getContikiFirmwareFile().getName() + - ": offsetting Cooja mote address space: " + offset); + logger.info(getContikiFirmwareFile().getName() + + ": offsetting Cooja mote address space: " + offset); } /* Create initial memory: data+bss+optional common */ @@ -540,7 +547,7 @@ public class ContikiMoteType implements MoteType { if (readonlySectionAddr >= 0 && readonlySectionSize > 0) { byte[] readonlySection = new byte[readonlySectionSize]; getCoreMemory(readonlySectionAddr, readonlySectionSize, readonlySection); - initialMemory.setReadonlyMemorySegment(readonlySectionAddr+offset, readonlySection); + initialMemory.setReadonlyMemorySegment(readonlySectionAddr + offset, readonlySection); } } @@ -568,13 +575,13 @@ public class ContikiMoteType implements MoteType { * but instead via ContikiMote.setMemory(). * * @param mem - * New memory + * New memory */ public void setCoreMemory(SectionMoteMemory mem) { for (int i = 0; i < mem.getNumberOfSections(); i++) { setCoreMemory( - mem.getSectionNativeAddress(i) /* native address space */, - mem.getSizeOfSection(i), mem.getDataOfSection(i)); + mem.getSectionNativeAddress(i) /* native address space */, + mem.getSizeOfSection(i), mem.getDataOfSection(i)); } } @@ -583,9 +590,9 @@ public class ContikiMoteType implements MoteType { * mappings are added to the given properties object. * * @param mapFileData - * Contents of entire map file + * Contents of entire map file * @param varAddresses - * Properties that should contain the name to addresses mappings. + * Properties that should contain the name to addresses mappings. */ public static boolean parseMapFileData(String[] mapFileData, HashMap varAddresses) { String[] varNames = getMapFileVarNames(mapFileData); @@ -599,7 +606,7 @@ public class ContikiMoteType implements MoteType { varAddresses.put(varName, new Integer(varAddress)); } else { logger.warn("Parsed Contiki variable '" + varName - + "' but could not find address"); + + "' but could not find address"); } } @@ -616,8 +623,8 @@ public class ContikiMoteType implements MoteType { public static boolean parseCommandData(String[] output, HashMap addresses) { int nrNew = 0, nrOld = 0, nrMismatch = 0; - Pattern pattern = - Pattern.compile(Cooja.getExternalToolsSetting("COMMAND_VAR_NAME_ADDRESS")); + Pattern pattern + = Pattern.compile(Cooja.getExternalToolsSetting("COMMAND_VAR_NAME_ADDRESS")); for (String line : output) { Matcher matcher = pattern.matcher(line); @@ -634,7 +641,7 @@ public class ContikiMoteType implements MoteType { int oldAddress = addresses.get(symbol); if (oldAddress != address) { /*logger.warn("Warning, command response not matching previous entry of: " - + varName);*/ + + varName);*/ nrMismatch++; } nrOld++; @@ -643,14 +650,13 @@ public class ContikiMoteType implements MoteType { } /*if (nrMismatch > 0) { - logger.debug("Command response parsing summary: Added " + nrNew - + " variables. Found " + nrOld - + " old variables. Mismatching addresses: " + nrMismatch); - } else { - logger.debug("Command response parsing summary: Added " + nrNew - + " variables. Found " + nrOld + " old variables"); - }*/ - + logger.debug("Command response parsing summary: Added " + nrNew + + " variables. Found " + nrOld + + " old variables. Mismatching addresses: " + nrMismatch); + } else { + logger.debug("Command response parsing summary: Added " + nrNew + + " variables. Found " + nrOld + " old variables"); + }*/ return (nrNew + nrOld) > 0; } @@ -659,11 +665,12 @@ public class ContikiMoteType implements MoteType { * instead via ContikiMote.getMemory(). * * @param mem - * Memory to set + * Memory to set */ public void getCoreMemory(SectionMoteMemory mem) { for (int i = 0; i < mem.getNumberOfSections(); i++) { int startAddr = mem.getSectionNativeAddress(i); /* native address space */ + int size = mem.getSizeOfSection(i); byte[] data = mem.getDataOfSection(i); getCoreMemory(startAddr, size, data); @@ -750,10 +757,10 @@ public class ContikiMoteType implements MoteType { return varAddrInteger.intValue(); } - String regExp = - Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_1") + - varName + - Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_2"); + String regExp + = Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_1") + + varName + + Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_2"); String retString = getFirstMatchGroup(mapFileData, regExp, 1); if (retString != null) { @@ -792,37 +799,35 @@ public class ContikiMoteType implements MoteType { * @return Variable names found in the data and bss section */ public static String[] getMapFileVarNames(String[] mapFileData) { - ArrayList varNames = new ArrayList(); + ArrayList varNames = new ArrayList<>(); String[] dataVariables = getAllVariableNames( - mapFileData, - parseMapDataSectionAddr(mapFileData), - parseMapDataSectionAddr(mapFileData) + parseMapDataSectionSize(mapFileData)); - for (String v: dataVariables) { + mapFileData, + parseMapDataSectionAddr(mapFileData), + parseMapDataSectionAddr(mapFileData) + parseMapDataSectionSize(mapFileData)); + for (String v : dataVariables) { varNames.add(v); } String[] bssVariables = getAllVariableNames( - mapFileData, - parseMapBssSectionAddr(mapFileData), - parseMapBssSectionAddr(mapFileData) + parseMapBssSectionSize(mapFileData)); - for (String v: bssVariables) { - varNames.add(v); - } + mapFileData, + parseMapBssSectionAddr(mapFileData), + parseMapBssSectionAddr(mapFileData) + parseMapBssSectionSize(mapFileData)); + varNames.addAll(Arrays.asList(bssVariables)); return varNames.toArray(new String[0]); } private static String[] getAllVariableNames(String[] lines, - int startAddress, int endAddress) { - ArrayList varNames = new ArrayList(); + int startAddress, int endAddress) { + ArrayList varNames = new ArrayList<>(); Pattern pattern = Pattern.compile(Cooja.getExternalToolsSetting("MAPFILE_VAR_NAME")); for (String line : lines) { Matcher matcher = pattern.matcher(line); if (matcher.find()) { if (Integer.decode(matcher.group(1)).intValue() >= startAddress - && Integer.decode(matcher.group(1)).intValue() <= endAddress) { + && Integer.decode(matcher.group(1)).intValue() <= endAddress) { varNames.add(matcher.group(2)); } } @@ -832,9 +837,9 @@ public class ContikiMoteType implements MoteType { protected int getVariableSize(Vector lines, String varName) { Pattern pattern = Pattern.compile( - Cooja.getExternalToolsSetting("MAPFILE_VAR_SIZE_1") + - varName + - Cooja.getExternalToolsSetting("MAPFILE_VAR_SIZE_2")); + Cooja.getExternalToolsSetting("MAPFILE_VAR_SIZE_1") + + varName + + Cooja.getExternalToolsSetting("MAPFILE_VAR_SIZE_2")); for (int i = 0; i < lines.size(); i++) { Matcher matcher = pattern.matcher(lines.get(i)); if (matcher.find()) { @@ -845,8 +850,8 @@ public class ContikiMoteType implements MoteType { } private static int parseFirstHexInt(String regexp, String[] data) { - String retString = - getFirstMatchGroup(data, regexp, 1); + String retString + = getFirstMatchGroup(data, regexp, 1); if (retString != null) { return Integer.parseInt(retString.trim(), 16); @@ -862,6 +867,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, mapFileData); } + public static int parseMapDataSectionSize(String[] mapFileData) { String regexp = Cooja.getExternalToolsSetting("MAPFILE_DATA_SIZE", ""); if (regexp.equals("")) { @@ -869,6 +875,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, mapFileData); } + public static int parseMapBssSectionAddr(String[] mapFileData) { String regexp = Cooja.getExternalToolsSetting("MAPFILE_BSS_START", ""); if (regexp.equals("")) { @@ -876,6 +883,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, mapFileData); } + public static int parseMapBssSectionSize(String[] mapFileData) { String regexp = Cooja.getExternalToolsSetting("MAPFILE_BSS_SIZE", ""); if (regexp.equals("")) { @@ -883,6 +891,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, mapFileData); } + public static int parseMapCommonSectionAddr(String[] mapFileData) { String regexp = Cooja.getExternalToolsSetting("MAPFILE_COMMON_START", ""); if (regexp.equals("")) { @@ -890,6 +899,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, mapFileData); } + public static int parseMapCommonSectionSize(String[] mapFileData) { String regexp = Cooja.getExternalToolsSetting("MAPFILE_COMMON_SIZE", ""); if (regexp.equals("")) { @@ -905,6 +915,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, output); } + public static int parseCommandDataSectionSize(String[] output) { String regexp = Cooja.getExternalToolsSetting("COMMAND_DATA_END", ""); if (regexp.equals("")) { @@ -921,6 +932,7 @@ public class ContikiMoteType implements MoteType { } return end - start; } + public static int parseCommandBssSectionAddr(String[] output) { String regexp = Cooja.getExternalToolsSetting("COMMAND_BSS_START", ""); if (regexp.equals("")) { @@ -928,6 +940,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, output); } + public static int parseCommandBssSectionSize(String[] output) { String regexp = Cooja.getExternalToolsSetting("COMMAND_BSS_END", ""); if (regexp.equals("")) { @@ -944,6 +957,7 @@ public class ContikiMoteType implements MoteType { } return end - start; } + public static int parseCommandCommonSectionAddr(String[] output) { String regexp = Cooja.getExternalToolsSetting("COMMAND_COMMON_START", ""); if (regexp.equals("")) { @@ -951,6 +965,7 @@ public class ContikiMoteType implements MoteType { } return parseFirstHexInt(regexp, output); } + public static int parseCommandCommonSectionSize(String[] output) { String regexp = Cooja.getExternalToolsSetting("COMMAND_COMMON_END", ""); if (regexp.equals("")) { @@ -971,6 +986,7 @@ public class ContikiMoteType implements MoteType { private static int parseCommandReadonlySectionAddr(String[] output) { return parseFirstHexInt("^([0-9A-Fa-f]*)[ \t]t[ \t].text$", output); } + private static int parseCommandReadonlySectionSize(String[] output) { int start = parseCommandReadonlySectionAddr(output); if (start < 0) { @@ -978,16 +994,16 @@ public class ContikiMoteType implements MoteType { } /* Extract the last specified address, assuming that the interval covers all the memory */ - String last = output[output.length-1]; - int lastAddress = Integer.parseInt(last.split("[ \t]")[0],16); + String last = output[output.length - 1]; + int lastAddress = Integer.parseInt(last.split("[ \t]")[0], 16); return lastAddress - start; } private static int getRelVarAddr(String mapFileData[], String varName) { - String regExp = - Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_1") + - varName + - Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_2"); + String regExp + = Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_1") + + varName + + Cooja.getExternalToolsSetting("MAPFILE_VAR_ADDRESS_2"); String retString = getFirstMatchGroup(mapFileData, regExp, 1); if (retString != null) { @@ -1012,7 +1028,7 @@ public class ContikiMoteType implements MoteType { * @return Execution response, or null at failure */ public static String[] loadCommandData(File libraryFile) { - ArrayList output = new ArrayList(); + ArrayList output = new ArrayList<>(); try { String command = Cooja.getExternalToolsSetting("PARSE_COMMAND"); @@ -1022,17 +1038,17 @@ public class ContikiMoteType implements MoteType { /* Prepare command */ command = command.replace("$(LIBFILE)", - libraryFile.getName().replace(File.separatorChar, '/')); + libraryFile.getName().replace(File.separatorChar, '/')); /* Execute command, read response */ String line; Process p = Runtime.getRuntime().exec( - command.split(" "), - null, - libraryFile.getParentFile() + command.split(" "), + null, + libraryFile.getParentFile() ); BufferedReader input = new BufferedReader( - new InputStreamReader(p.getInputStream()) + new InputStreamReader(p.getInputStream()) ); p.getErrorStream().close(); while ((line = input.readLine()) != null) { @@ -1040,11 +1056,11 @@ public class ContikiMoteType implements MoteType { } input.close(); - if (output == null || output.size() == 0) { + if (output == null || output.isEmpty()) { return null; } return output.toArray(new String[0]); - } catch (Exception err) { + } catch (IOException err) { logger.fatal("Command error: " + err.getMessage(), err); return null; } @@ -1070,7 +1086,7 @@ public class ContikiMoteType implements MoteType { * simulator project configuration. * * @param moteTypeConfig - * Project configuration + * Project configuration */ public void setConfig(ProjectConfig moteTypeConfig) { myConfig = moteTypeConfig; @@ -1098,7 +1114,7 @@ public class ContikiMoteType implements MoteType { * Set core interfaces * * @param coreInterfaces - * New core interfaces + * New core interfaces */ public void setCoreInterfaces(String[] coreInterfaces) { this.coreInterfaces = coreInterfaces; @@ -1116,10 +1132,8 @@ public class ContikiMoteType implements MoteType { @Override public void setMoteInterfaceClasses(Class[] moteInterfaces) { - this.moteInterfacesClasses = new ArrayList>(); - for (Class intf: moteInterfaces) { - this.moteInterfacesClasses.add(intf); - } + this.moteInterfacesClasses = new ArrayList<>(); + this.moteInterfacesClasses.addAll(Arrays.asList(moteInterfaces)); } /** @@ -1127,7 +1141,7 @@ public class ContikiMoteType implements MoteType { * when loading a saved simulation. * * @param file - * File containg data to checksum + * File containg data to checksum * @return Checksum */ protected byte[] createChecksum(File file) { @@ -1146,9 +1160,7 @@ public class ContikiMoteType implements MoteType { } } fileInputStream.close(); - } catch (NoSuchAlgorithmException e) { - return null; - } catch (IOException e) { + } catch (NoSuchAlgorithmException | IOException e) { return null; } return messageDigest.digest(); @@ -1195,8 +1207,8 @@ public class ContikiMoteType implements MoteType { // Check if identifier library has been loaded /* XXX Currently only checks the build directory! */ File libraryFile = new File( - ContikiMoteType.tempOutputDirectory, - testID + ContikiMoteType.librarySuffix); + ContikiMoteType.tempOutputDirectory, + testID + ContikiMoteType.librarySuffix); if (libraryFile.exists() || CoreComm.hasLibraryFileBeenLoaded(libraryFile)) { okID = false; } @@ -1215,41 +1227,41 @@ public class ContikiMoteType implements MoteType { StringBuilder sb = new StringBuilder(); // Identifier sb.append(""); + .append(getIdentifier()).append(""); // Description sb.append(""); + .append(getDescription()).append(""); /* Contiki application */ sb.append(""); + .append(getContikiSourceFile().getAbsolutePath()).append(""); /* Contiki firmware */ sb.append(""); + .append(getContikiFirmwareFile().getAbsolutePath()).append(""); /* JNI class */ sb.append(""); + .append(this.javaClassName).append(""); /* Contiki sensors */ sb.append(""); /* Mote interfaces */ sb.append(""); /* Contiki core mote interfaces */ sb.append(""); @@ -1261,7 +1273,7 @@ public class ContikiMoteType implements MoteType { @Override public Collection getConfigXML(Simulation simulation) { - ArrayList config = new ArrayList(); + ArrayList config = new ArrayList<>(); Element element; element = new Element("identifier"); @@ -1302,8 +1314,8 @@ public class ContikiMoteType implements MoteType { @Override public boolean setConfigXML(Simulation simulation, - Collection configXML, boolean visAvailable) - throws MoteTypeCreationException { + Collection configXML, boolean visAvailable) + throws MoteTypeCreationException { boolean warnedOldVersion = false; File oldVersionSource = null; @@ -1311,91 +1323,87 @@ public class ContikiMoteType implements MoteType { for (Element element : configXML) { String name = element.getName(); - - if (name.equals("identifier")) { - identifier = element.getText(); - } else if (name.equals("description")) { - description = element.getText(); - } else if (name.equals("contikiapp") || name.equals("source")) { - File file = new File(element.getText()); - if (!file.exists()) { - file = simulation.getCooja().restorePortablePath(file); - } - - setContikiSourceFile(file); - - /* XXX Do not load the generated firmware. Instead, load the unique library file directly */ + switch (name) { + case "identifier": + identifier = element.getText(); + break; + case "description": + description = element.getText(); + break; + case "contikiapp": + case "source": + File file = new File(element.getText()); + if (!file.exists()) { + file = simulation.getCooja().restorePortablePath(file); + } setContikiSourceFile(file); + /* XXX Do not load the generated firmware. Instead, load the unique library file directly */ File contikiFirmware = new File( - getContikiSourceFile().getParentFile(), - "obj_cooja/" + getIdentifier() + librarySuffix); - setContikiFirmwareFile(contikiFirmware); - - } else if (name.equals("commands")) { - compileCommands = element.getText(); - } else if (name.equals("symbols")) { - hasSystemSymbols = Boolean.parseBoolean(element.getText()); - } else if (name.equals("commstack")) { - logger.warn("The Cooja communication stack config was removed: " + element.getText()); - logger.warn("Instead assuming default network stack."); - netStack = NetworkStack.DEFAULT; - } else if (name.equals("netstack")) { - netStack = NetworkStack.parseConfig(element.getText()); - } else if (name.equals("moteinterface")) { - String intfClass = element.getText().trim(); - - /* Backwards compatibility: se.sics -> org.contikios */ - if (intfClass.startsWith("se.sics")) { - intfClass = intfClass.replaceFirst("se\\.sics", "org.contikios"); - } - - Class moteInterfaceClass = - simulation.getCooja().tryLoadClass( - this, MoteInterface.class, intfClass); - + getContikiSourceFile().getParentFile(), + "obj_cooja/" + getIdentifier() + librarySuffix); + setContikiFirmwareFile(contikiFirmware); + break; + case "commands": + compileCommands = element.getText(); + break; + case "symbols": + hasSystemSymbols = Boolean.parseBoolean(element.getText()); + break; + case "commstack": + logger.warn("The Cooja communication stack config was removed: " + element.getText()); + logger.warn("Instead assuming default network stack."); + netStack = NetworkStack.DEFAULT; + break; + case "netstack": + netStack = NetworkStack.parseConfig(element.getText()); + break; + case "moteinterface": + String intfClass = element.getText().trim(); + /* Backwards compatibility: se.sics -> org.contikios */ + if (intfClass.startsWith("se.sics")) { + intfClass = intfClass.replaceFirst("se\\.sics", "org.contikios"); + } Class moteInterfaceClass + = simulation.getCooja().tryLoadClass( + this, MoteInterface.class, intfClass); if (moteInterfaceClass == null) { logger.warn("Can't find mote interface class: " + intfClass); } else { moteInterfacesClasses.add(moteInterfaceClass); - } - } else if ( - name.equals("contikibasedir") || - name.equals("contikicoredir") || - name.equals("projectdir") || - name.equals("compilefile") || - name.equals("process") || - name.equals("sensor") || - name.equals("coreinterface")) { - /* Backwards compatibility: old cooja mote type is being loaded */ - if (!warnedOldVersion) { - warnedOldVersion = true; - logger.warn("Old simulation config detected: Cooja mote types may not load correctly"); - } - - if (name.equals("compilefile")) { + } break; + case "contikibasedir": + case "contikicoredir": + case "projectdir": + case "compilefile": + case "process": + case "sensor": + case "coreinterface": + /* Backwards compatibility: old cooja mote type is being loaded */ + if (!warnedOldVersion) { + warnedOldVersion = true; + logger.warn("Old simulation config detected: Cooja mote types may not load correctly"); + } if (name.equals("compilefile")) { if (element.getText().endsWith(".c")) { File potentialFile = new File(element.getText()); if (potentialFile.exists()) { oldVersionSource = potentialFile; } } - } - - } else { - logger.fatal("Unrecognized entry in loaded configuration: " + name); + } break; + default: + logger.fatal("Unrecognized entry in loaded configuration: " + name); + break; } } /* Create initial core interface dependencies */ - Class[] arr = - new Class[moteInterfacesClasses.size()]; + Class[] arr + = new Class[moteInterfacesClasses.size()]; moteInterfacesClasses.toArray(arr); setCoreInterfaces(ContikiMoteType.getRequiredCoreInterfaces(arr)); /* Backwards compatibility: old cooja mote type is being loaded */ - if (getContikiSourceFile() == null && - warnedOldVersion && - oldVersionSource != null) - { + if (getContikiSourceFile() == null + && warnedOldVersion + && oldVersionSource != null) { /* Guess Contiki source */ setContikiSourceFile(oldVersionSource); logger.info("Guessing Contiki source: " + oldVersionSource.getAbsolutePath()); @@ -1404,8 +1412,8 @@ public class ContikiMoteType implements MoteType { logger.info("Guessing Contiki firmware: " + getContikiFirmwareFile().getAbsolutePath()); /* Guess compile commands */ - String compileCommands = - "make " + getExpectedFirmwareFile(oldVersionSource).getName() + " TARGET=cooja"; + String compileCommands + = "make " + getExpectedFirmwareFile(oldVersionSource).getName() + " TARGET=cooja"; logger.info("Guessing compile commands: " + compileCommands); setCompileCommands(compileCommands); } @@ -1415,10 +1423,10 @@ public class ContikiMoteType implements MoteType { } public static String[] getRequiredCoreInterfaces( - Class[] moteInterfaces) { + Class[] moteInterfaces) { /* Extract Contiki dependencies from currently selected mote interfaces */ - ArrayList coreInterfacesList = new ArrayList(); - for (Class intf: moteInterfaces) { + ArrayList coreInterfacesList = new ArrayList<>(); + for (Class intf : moteInterfaces) { if (!ContikiMoteInterface.class.isAssignableFrom(intf)) { continue; } @@ -1437,10 +1445,7 @@ public class ContikiMoteType implements MoteType { if (deps == null || deps.length == 0) { continue; } - - for (String dep: deps) { - coreInterfacesList.add(dep); - } + coreInterfacesList.addAll(Arrays.asList(deps)); } String[] coreInterfaces = new String[coreInterfacesList.size()];
Identifier") - .append(getIdentifier()).append("
Description") - .append(getDescription()).append("
Contiki application") - .append(getContikiSourceFile().getAbsolutePath()).append("
Contiki firmware") - .append(getContikiFirmwareFile().getAbsolutePath()).append("
JNI library") - .append(this.javaClassName).append("
Contiki sensors"); - for (String sensor: sensors) { + for (String sensor : sensors) { sb.append(sensor).append("
"); } sb.append("
Mote interface"); - for (Class moteInterface: moteInterfacesClasses) { + for (Class moteInterface : moteInterfacesClasses) { sb.append(moteInterface.getSimpleName()).append("
"); } sb.append("
Contiki's mote interface"); - for (String coreInterface: getCoreInterfaces()) { + for (String coreInterface : getCoreInterfaces()) { sb.append(coreInterface).append("
"); } sb.append("