예제 #1
0
  private void cleanupClient() {
    try {
      if (client != null) {
        client.close();
        client = null;
      }
    } catch (IOException e1) {
    }
    try {
      if (in != null) {
        in.close();
        in = null;
      }
    } catch (IOException e) {
    }
    try {
      if (out != null) {
        out.close();
        out = null;
      }
    } catch (IOException e) {
    }

    if (GUI.isVisualized()) {
      SwingUtilities.invokeLater(
          new Runnable() {
            public void run() {
              statusLabel.setText("Listening on port: " + LISTEN_PORT);
            }
          });
    }
  }
예제 #2
0
  private static void handleExportAttributesFromJAR(Element e, File config, File toDir) {
    for (Element c : ((List<Element>) e.getChildren()).toArray(new Element[0])) {
      Attribute a = c.getAttribute("EXPORT");
      if (a != null && a.getValue().equals("copy")) {
        /* Copy file from JAR */
        File file = GUI.restoreConfigRelativePath(config, new File(c.getText()));
        InputStream inputStream = GUI.class.getResourceAsStream("/" + file.getName());
        if (inputStream == null) {
          throw new RuntimeException("Could not unpack file: " + file);
        }
        byte[] fileData = ArrayUtils.readFromStream(inputStream);
        if (fileData == null) {
          logger.info("Failed unpacking file");
          throw new RuntimeException("Could not unpack file: " + file);
        }
        if (OVERWRITE || !file.exists()) {
          boolean ok = ArrayUtils.writeToFile(file, fileData);
          if (!ok) {
            throw new RuntimeException("Failed unpacking file: " + file);
          }
          logger.info("Unpacked file from JAR: " + file.getName());
        } else if (OVERWRITE) {
          logger.info("Skip: unpack file from JAR: " + file.getName());
        }
      }

      /* Recursive search */
      handleExportAttributesFromJAR(c, config, toDir);
    }
  }
 public String getDefaultCompileCommands(File source) {
   /* TODO Split into String[] */
   return GUI.getExternalToolsSetting("PATH_MAKE")
       + " "
       + getExpectedFirmwareFile(source).getName()
       + " TARGET="
       + target;
 }
예제 #4
0
  /**
   * Prepares CPU, memory and ELF module.
   *
   * @param fileELF ELF file
   * @param cpu MSP430 cpu
   * @throws IOException Preparing mote failed
   */
  protected void prepareMote(File fileELF, GenericNode node) throws IOException {
    LineOutputStream lout =
        new LineOutputStream(
            new LineListener() {
              @Override
              public void lineRead(String line) {
                LineListener listener = commandListener;
                if (listener != null) {
                  listener.lineRead(line);
                }
              }
            });
    PrintStream out = new PrintStream(lout);
    this.commandHandler = new CommandHandler(out, out);
    node.setCommandHandler(commandHandler);

    ConfigManager config = new ConfigManager();
    node.setup(config);

    this.myCpu = node.getCPU();
    this.myCpu.setMonitorExec(true);

    int[] memory = myCpu.getMemory();
    if (GUI.isVisualizedInApplet()) {
      myELFModule = node.loadFirmware(new URL(GUI.getAppletCodeBase(), fileELF.getName()), memory);
    } else {
      myELFModule = node.loadFirmware(fileELF.getPath(), memory);
    }

    /* Throw exceptions at bad memory access */
    /*myCpu.setThrowIfWarning(true);*/

    /* Create mote address memory */
    MapTable map = myELFModule.getMap();
    MapEntry[] allEntries = map.getAllEntries();
    myMemory = new MspMoteMemory(allEntries, myCpu);

    heapStartAddress = map.heapStartAddress;
    myCpu.reset();
  }
예제 #5
0
  private static void handleExportAttributesToJAR(Element e, GUI gui, File toDir) {
    /* Checks configuration for EXPORT attributes:
     * copy: file copy file to exported JAR, update file path.
     * discard: remove config element */

    for (Element c : ((List<Element>) e.getChildren()).toArray(new Element[0])) {
      Attribute a = c.getAttribute("EXPORT");
      if (a != null && a.getValue().equals("copy")) {
        /* Copy file to JAR */
        File file = gui.restorePortablePath(new File(c.getText()));
        if (!file.exists()) {
          throw new RuntimeException("File not found: " + file);
        }
        byte[] data = ArrayUtils.readFromFile(file);
        if (data == null) {
          throw new RuntimeException("Could not copy file: " + file);
        }

        String newFilename = file.getName();
        while (new File(toDir, newFilename).exists()) {
          newFilename += "-1";
        }
        boolean ok = ArrayUtils.writeToFile(new File(toDir, newFilename), data);
        if (!ok) {
          throw new RuntimeException("Error when copying file: " + file);
        }
        logger.info(
            "Simconfig: Copied file: "
                + file.getAbsolutePath()
                + " -> "
                + ("[CONFIG_DIR]/" + newFilename));
        ((Element) c).setText("[CONFIG_DIR]/" + newFilename);
      } else if (a != null && a.getValue().equals("discard")) {
        /* Remove config element */
        e.removeChild(c.getName());
        logger.info("Simconfig: Discarded element '" + c.getName() + "': " + c.getText());
        continue;
      } else if (a != null) {
        throw new RuntimeException("Unknown EXPORT attribute value: " + a.getValue());
      }

      /* Recursive search */
      handleExportAttributesToJAR(c, gui, toDir);
    }
  }
예제 #6
0
  /**
   * Prepares CPU, memory and ELF module.
   *
   * @param fileELF ELF file
   * @param cpu MSP430 cpu
   * @throws IOException Preparing mote failed
   */
  protected void prepareMote(File fileELF, GenericNode node) throws IOException {
    LineOutputStream lout =
        new LineOutputStream(
            new LineListener() {
              public void lineRead(String line) {
                for (LineListener l : commandListeners.toArray(new LineListener[0])) {
                  if (l == null) {
                    continue;
                  }
                  l.lineRead(line);
                }
              }
            });
    PrintStream out = new PrintStream(lout);
    this.commandHandler = new CommandHandler(out, out);
    node.setCommandHandler(commandHandler);

    ConfigManager config = new ConfigManager();
    node.setup(config);

    this.myCpu = node.getCPU();
    this.myCpu.setMonitorExec(true);
    this.myCpu.setTrace(0); /* TODO Enable */

    int[] memory = myCpu.getMemory();
    logger.info("Loading firmware from: " + fileELF.getAbsolutePath());
    GUI.setProgressMessage("Loading " + fileELF.getName());
    node.loadFirmware(((MspMoteType) getType()).getELF(), memory);

    /* Throw exceptions at bad memory access */
    /*myCpu.setThrowIfWarning(true);*/

    /* Create mote address memory */
    MapTable map = ((MspMoteType) getType()).getELF().getMap();
    MapEntry[] allEntries = map.getAllEntries();
    myMemory = new MspMoteMemory(allEntries, myCpu);

    heapStartAddress = map.heapStartAddress;
    myCpu.reset();
  }
예제 #7
0
  private static void generate(File config, File jar) {
    if (!config.exists()) {
      throw new RuntimeException("Simulation config not found: " + config.getAbsolutePath());
    }

    /* Load simulation */
    logger.info("Loading " + config);
    GUI.externalToolsUserSettingsFile =
        new File(System.getProperty("user.home"), GUI.EXTERNAL_TOOLS_USER_SETTINGS_FILENAME);
    Simulation s = GUI.quickStartSimulationConfig(config, false, null);
    if (s == null) {
      throw new RuntimeException("Error when creating simulation");
    }
    s.stopSimulation();

    try {
      buildExecutableJAR(s.getGUI(), jar);
    } catch (RuntimeException e) {
      logger.fatal(e.getMessage(), e);
      System.exit(1);
    }
    System.exit(0);
  }
예제 #8
0
  /**
   * Builds executable JAR from current simulation
   *
   * @param gui GUI. Must contain simulation
   * @param outputFile Output file
   */
  public static boolean buildExecutableJAR(GUI gui, File outputFile) {
    String executeDir = null;
    executeDir = outputFile.getName();
    if (!executeDir.endsWith(".jar")) {
      throw new RuntimeException("Not a proper JAR archive: " + executeDir);
    }
    executeDir = executeDir.substring(0, executeDir.length() - ".jar".length());

    Simulation simulation = gui.getSimulation();
    if (simulation == null) {
      throw new RuntimeException("No simulation active");
    }

    /* Check dependencies: mote type */
    for (MoteType t : simulation.getMoteTypes()) {
      if (!t.getClass().getName().contains("SkyMoteType")) {
        throw new RuntimeException(
            "You simulation contains the mote type: "
                + GUI.getDescriptionOf(t.getClass())
                + "\n"
                + "Only the Sky Mote Type is currently supported.\n");
      }
      logger.info("Checking mote types: '" + GUI.getDescriptionOf(t.getClass()) + "'");
    }

    /* Check dependencies: Contiki Test Editor */
    boolean hasTestEditor = false;
    for (Plugin startedPlugin : gui.getStartedPlugins()) {
      if (startedPlugin instanceof ScriptRunner) {
        hasTestEditor = true;
        break;
      }
    }
    logger.info("Checking that Contiki Test Editor exists: " + hasTestEditor);
    if (!hasTestEditor) {
      throw new RuntimeException(
          "The simulation needs at least one active Contiki Test Editor plugin.\n"
              + "The plugin is needed to control the non-visualized simulation.");
    }

    /* Create temporary directory */
    File workingDir;
    try {
      workingDir = File.createTempFile("cooja", ".tmp");
      workingDir.delete();
      workingDir.mkdir();
      logger.info("Creating temporary directory: " + workingDir.getAbsolutePath());
    } catch (IOException e1) {
      throw (RuntimeException)
          new RuntimeException("Error when creating temporary directory: " + e1.getMessage())
              .initCause(e1);
    }

    /* Unpacking project JARs */
    ProjectConfig config = gui.getProjectConfig();
    String[] projectJARs = config.getStringArrayValue(GUI.class.getName() + ".JARFILES");
    for (String jar : projectJARs) {
      /* Locate project */
      File project = config.getUserProjectDefining(GUI.class, "JARFILES", jar);
      File jarFile = new File(project, jar);
      if (!jarFile.exists()) {
        jarFile = new File(project, "lib/" + jar);
      }
      if (!jarFile.exists()) {
        throw new RuntimeException("Project JAR could not be found: " + jarFile.getAbsolutePath());
      }

      logger.info("Unpacking project JAR " + jar + " (" + project + ")");
      try {
        Process unjarProcess =
            Runtime.getRuntime()
                .exec(new String[] {"jar", "xf", jarFile.getAbsolutePath()}, null, workingDir);
        unjarProcess.waitFor();
      } catch (Exception e1) {
        throw (RuntimeException)
            new RuntimeException("Error unpacking JAR file: " + e1.getMessage()).initCause(e1);
      }
    }

    /* Unpacking COOJA core JARs */
    String[] coreJARs =
        new String[] {
          "tools/cooja/lib/jdom.jar", "tools/cooja/lib/log4j.jar", "tools/cooja/dist/cooja.jar"
        };
    for (String jar : coreJARs) {
      File jarFile = new File(GUI.getExternalToolsSetting("PATH_CONTIKI"), jar);
      if (!jarFile.exists()) {
        throw new RuntimeException("Project JAR could not be found: " + jarFile.getAbsolutePath());
      }
      logger.info("Unpacking core JAR " + jar);
      try {
        Process unjarProcess =
            Runtime.getRuntime()
                .exec(new String[] {"jar", "xf", jarFile.getAbsolutePath()}, null, workingDir);
        unjarProcess.waitFor();
      } catch (Exception e1) {
        throw (RuntimeException)
            new RuntimeException("Error unpacking JAR file: " + e1.getMessage()).initCause(e1);
      }
    }

    /* Prepare simulation config */
    Element rootElement = gui.extractSimulationConfig();
    logger.info("Extracting simulation configuration");
    handleExportAttributesToJAR(rootElement, gui, workingDir);

    /* Save simulation config */
    File configFile = new File(workingDir, SIMCONFIG_FILENAME);
    try {
      Document doc = new Document(rootElement);
      FileOutputStream out = new FileOutputStream(configFile);
      XMLOutputter outputter = new XMLOutputter();
      outputter.setFormat(Format.getPrettyFormat());
      outputter.output(doc, out);
      out.close();
    } catch (Exception e1) {
      throw (RuntimeException)
          new RuntimeException("Error when writing simulation configuration: " + configFile)
              .initCause(e1);
    }
    logger.info("Wrote simulation configuration: " + configFile.getName());

    /* Export external tools config (without projects) */
    try {
      File externalToolsConfig = new File(workingDir, EXTERNALTOOLS_FILENAME);
      FileOutputStream out = new FileOutputStream(externalToolsConfig);
      Properties differingSettings = new Properties();
      Enumeration<Object> keyEnum = GUI.currentExternalToolsSettings.keys();
      while (keyEnum.hasMoreElements()) {
        String key = (String) keyEnum.nextElement();
        String defaultSetting = GUI.getExternalToolsDefaultSetting(key, "");
        String currentSetting = GUI.currentExternalToolsSettings.getProperty(key, "");

        if (key.equals("DEFAULT_PROJECTDIRS")) {
          differingSettings.setProperty(key, "");
        } else if (!defaultSetting.equals(currentSetting)) {
          differingSettings.setProperty(key, currentSetting);
        }
      }

      differingSettings.store(out, "Cooja External Tools (User specific)");
      out.close();
      logger.info("Wrote external tools config: " + externalToolsConfig.getName());
    } catch (Exception e2) {
      throw (RuntimeException)
          new RuntimeException(
                  "Error when writing external tools configuration: " + e2.getMessage())
              .initCause(e2);
    }

    /* Export current project configuration */
    try {
      ProjectConfig pConfig = gui.getProjectConfig().clone();
      Enumeration<String> pValues = pConfig.getPropertyNames();
      File newConfigFile = new File(workingDir, PROJECT_DEFAULT_CONFIG_FILENAME);
      Properties newConfig = new Properties();
      while (pValues.hasMoreElements()) {
        String name = pValues.nextElement();
        newConfig.setProperty(name, pConfig.getStringValue(name));
      }
      FileOutputStream out = new FileOutputStream(newConfigFile);
      newConfig.store(out, "Cooja Project Config");
      logger.info("Wrote project config: " + newConfigFile.getName());
    } catch (Exception e1) {
      e1.printStackTrace();
      throw (RuntimeException)
          new RuntimeException("Error when writing project config: " + e1.getMessage())
              .initCause(e1);
    }

    /* Delete existing META-INF dir */
    File metaInfDir = new File(workingDir, "META-INF");
    if (metaInfDir.exists() && metaInfDir.isDirectory()) {
      if (!deleteDirectory(metaInfDir)) {
        if (!deleteDirectory(metaInfDir)) {
          deleteDirectory(metaInfDir);
        }
      }
    }

    /* Prepare JAR manifest */
    File manifestFile = new File(workingDir, "manifest.tmp");
    if (manifestFile.exists()) {
      manifestFile.delete();
    }
    StringBuilder sb = new StringBuilder();
    sb.append("Manifest-Version: 1.0\r\n");
    sb.append("Main-Class: " + ExecuteJAR.class.getName() + "\r\n");
    sb.append("Class-path: .\r\n");
    StringUtils.saveToFile(manifestFile, sb.toString());
    logger.info("Wrote manifest file: " + manifestFile.getName());

    /* Build executable JAR */
    if (outputFile.exists()) {
      outputFile.delete();
    }

    logger.info("Building executable JAR: " + outputFile);
    MessageList errors = new MessageList();
    try {
      CompileContiki.compile(
          "jar cfm " + outputFile.getAbsolutePath() + " manifest.tmp .",
          null,
          outputFile,
          workingDir,
          null,
          null,
          errors,
          true);
    } catch (Exception e) {
      logger.warn("Building executable JAR error: " + e.getMessage());
      MessageContainer[] err = errors.getMessages();
      for (int i = 0; i < err.length; i++) {
        logger.fatal(">> " + err[i]);
      }

      /* Forward exception */
      throw (RuntimeException)
          new RuntimeException("Error when building executable JAR: " + e.getMessage())
              .initCause(e);
    }

    /* Delete temporary working directory */
    logger.info("Deleting temporary files in: " + workingDir.getAbsolutePath());
    if (!deleteDirectory(workingDir)) {
      if (!deleteDirectory(workingDir)) {
        deleteDirectory(workingDir);
      }
    }

    /* We are done! */
    logger.info("Done! To run simulation: > java -jar " + outputFile.getName());
    return true;
  }
예제 #9
0
  private static void execute() {
    String executeDir = null;
    try {
      executeDir =
          new File(ExecuteJAR.class.getProtectionDomain().getCodeSource().getLocation().toURI())
              .getName();
      if (!executeDir.endsWith(".jar")) {
        logger.fatal("Not a proper JAR archive: " + executeDir);
        System.exit(1);
      }
      executeDir = executeDir.substring(0, executeDir.length() - ".jar".length());
      new File(executeDir).mkdir();
    } catch (URISyntaxException e1) {
      logger.fatal("Can't access JAR file name: " + e1.getMessage());
      System.exit(1);
    }

    /* Unpack JAR dependencies - only when they do not already exist! */
    try {
      InputStream inputStream;
      File diskFile = new File(executeDir, SIMCONFIG_FILENAME);
      if (OVERWRITE || !diskFile.exists()) {
        logger.info(
            "Unpacking simulation config: " + SIMCONFIG_FILENAME + " -> " + diskFile.getName());
        inputStream = GUI.class.getResourceAsStream("/" + SIMCONFIG_FILENAME);
        byte[] fileData = ArrayUtils.readFromStream(inputStream);
        if (fileData == null) {
          logger.info("Failed extracting file (read fail)");
          System.exit(1);
        }
        boolean ok = ArrayUtils.writeToFile(diskFile, fileData);
        if (!ok) {
          logger.info("Failed extracting file (write fail)");
          System.exit(1);
        }
      } else {
        logger.info("Skip: simulation config already exists: " + diskFile);
      }

      diskFile = new File(executeDir, EXTERNALTOOLS_FILENAME);
      if (OVERWRITE || !diskFile.exists()) {
        logger.info(
            "Unpacking external tools config: "
                + EXTERNALTOOLS_FILENAME
                + " -> "
                + diskFile.getName());
        inputStream = GUI.class.getResourceAsStream("/" + EXTERNALTOOLS_FILENAME);
        byte[] fileData = ArrayUtils.readFromStream(inputStream);
        if (fileData == null) {
          logger.info("Failed extracting file (read fail)");
          System.exit(1);
        }
        boolean ok = ArrayUtils.writeToFile(diskFile, fileData);
        if (!ok) {
          logger.info("Failed extracting file (write fail)");
          System.exit(1);
        }
      } else {
        logger.info("Skip: external tools config already exists: " + diskFile);
      }
      GUI.externalToolsUserSettingsFile = diskFile;

      /* Unpack files from JAR (with attribute EXPORT=copy) */
      SAXBuilder builder = new SAXBuilder();
      Document doc = builder.build(new File(executeDir, SIMCONFIG_FILENAME));
      handleExportAttributesFromJAR(
          doc.getRootElement(), new File(executeDir, SIMCONFIG_FILENAME), new File(executeDir));
    } catch (Exception e) {
      logger.fatal("Error when unpacking executable JAR: " + e.getMessage());
      return;
    }

    logger.info("Starting simulation");
    GUI.setLookAndFeel();
    GUI.quickStartSimulationConfig(new File(executeDir, SIMCONFIG_FILENAME), false, null);
  }
  public PowerTracker(final Simulation simulation, final GUI gui) {
    super("PowerTracker", gui, false);
    this.simulation = simulation;

    /* Automatically add/delete motes */
    simulation
        .getEventCentral()
        .addMoteCountListener(
            moteCountListener =
                new MoteCountListener() {
                  public void moteWasAdded(Mote mote) {
                    addMote(mote);
                    table.invalidate();
                    table.repaint();
                  }

                  public void moteWasRemoved(Mote mote) {
                    removeMote(mote);
                    table.invalidate();
                    table.repaint();
                  }
                });
    for (Mote m : simulation.getMotes()) {
      addMote(m);
    }

    if (!GUI.isVisualized()) {
      return;
    }

    AbstractTableModel model =
        new AbstractTableModel() {
          public int getRowCount() {
            return moteTrackers.size() + 1;
          }

          public int getColumnCount() {
            return 4;
          }

          public String getColumnName(int col) {
            if (col == COLUMN_MOTE) {
              return "Mote";
            }
            if (col == COLUMN_RADIOON) {
              return "Radio on (%)";
            }
            if (col == COLUMN_RADIOTX) {
              return "Radio TX (%)";
            }
            if (col == COLUMN_RADIORX) {
              return "Radio RX (%)";
            }
            return null;
          }

          public Object getValueAt(int rowIndex, int col) {
            if (rowIndex < 0 || rowIndex >= moteTrackers.size() + 1) {
              return null;
            }

            if (rowIndex == moteTrackers.size()) {
              /* Average */
              long radioOn = 0;
              long radioTx = 0;
              long radioRx = 0;
              long duration = 0;
              for (MoteTracker mt : moteTrackers) {
                radioOn += mt.radioOn;
                radioTx += mt.radioTx;
                radioRx += mt.radioRx;

                duration += mt.duration;
              }

              if (col == COLUMN_MOTE) {
                return "AVERAGE";
              }
              if (col == COLUMN_RADIOON) {
                return String.format("%2.2f%%", 100.0 * radioOn / duration);
              }
              if (col == COLUMN_RADIOTX) {
                return String.format("%2.2f%%", 100.0 * radioTx / duration);
              }
              if (col == COLUMN_RADIORX) {
                return String.format("%2.2f%%", 100.0 * radioRx / duration);
              }
              return null;
            }

            MoteTracker rule = moteTrackers.get(rowIndex);
            if (col == COLUMN_MOTE) {
              return rule.mote.toString();
            }
            if (col == COLUMN_RADIOON) {
              return String.format("%2.2f%%", 100.0 * rule.getRadioOnRatio());
            }
            if (col == COLUMN_RADIOTX) {
              return String.format("%2.2f%%", 100.0 * rule.getRadioTxRatio());
            }
            if (col == COLUMN_RADIORX) {
              return String.format("%2.2f%%", 100.0 * rule.getRadioRxRatio());
            }
            return null;
          }
        };
    table =
        new JTable(model) {
          public String getToolTipText(MouseEvent e) {
            java.awt.Point p = e.getPoint();
            int rowIndex = table.rowAtPoint(p);
            if (rowIndex < 0 || rowIndex >= moteTrackers.size()) {
              return null;
            }
            MoteTracker mt = moteTrackers.get(rowIndex);
            return "<html><pre>" + mt.toString() + "</html>";
          }
        };
    table.setDefaultRenderer(
        Object.class,
        new DefaultTableCellRenderer() {
          public Component getTableCellRendererComponent(
              JTable table,
              Object value,
              boolean isSelected,
              boolean hasFocus,
              int row,
              int column) {
            Component c =
                super.getTableCellRendererComponent(
                    table, value, isSelected, hasFocus, row, column);
            if (row == tableMaxRadioOnIndex) {
              setBackground(isSelected ? table.getSelectionBackground() : Color.RED);
              setForeground(isSelected ? table.getSelectionForeground() : Color.WHITE);
            } else {
              setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
              setForeground(isSelected ? table.getSelectionForeground() : table.getForeground());
            }
            return c;
          }
        });

    Box control = Box.createHorizontalBox();
    control.add(Box.createHorizontalGlue());
    control.add(new JButton(printAction));
    control.add(new JButton(resetAction));

    this.getContentPane().add(BorderLayout.CENTER, new JScrollPane(table));
    this.getContentPane().add(BorderLayout.SOUTH, control);
    setSize(400, 400);

    repaintTimer.start();
  }
  public GISOO_Simulink_Plugin(Mote mote, Simulation simulation, final GUI gui) {

    super("GISOO-Simulink Plugin (" + mote + ")", gui, false);
    this.mote = mote;
    skyMote = (SkyMote) mote;
    sim = skyMote.getSimulation();
    LISTEN_PORT = 18000 + mote.getID();

    if (GUI.isVisualized()) {
      this.getContentPane().setSize(100, 100);
      Box northBox = Box.createHorizontalBox();
      northBox.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
      JPanel smallPanel = new JPanel(new BorderLayout());
      JLabel label = new JLabel("Listening on port: " + LISTEN_PORT);
      label.setPreferredSize(new Dimension(LABEL_WIDTH, 20));
      smallPanel.add(BorderLayout.CENTER, label);
      northBox.add(smallPanel);

      Box mainBox = Box.createHorizontalBox();
      mainBox.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
      JPanel smallPane = new JPanel(new BorderLayout());
      JLabel simulinkPort = new JLabel("Sending data to port: " + SIMULINK_PORT);
      simulinkPort.setPreferredSize(new Dimension(LABEL_WIDTH, LABEL_HEIGHT));
      smallPane.add(BorderLayout.CENTER, simulinkPort);
      mainBox.add(smallPane);

      Box southernBox = Box.createHorizontalBox();
      southernBox.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
      JPanel smallPane2 = new JPanel(new BorderLayout());
      serialDataShouldRCV = new JCheckBox("Serial reply should be received after(ms): ");
      CPUDellay = new JTextField("1");
      CPUDellay.setPreferredSize(new Dimension(LABEL_WIDTH, 25));
      smallPane2.add(BorderLayout.WEST, serialDataShouldRCV);
      smallPane2.add(BorderLayout.CENTER, CPUDellay);
      southernBox.add(smallPane2);

      getContentPane().add(BorderLayout.NORTH, northBox);
      getContentPane().add(BorderLayout.CENTER, mainBox);
      getContentPane().add(BorderLayout.SOUTH, southernBox);
      pack();
    }

    /* Mote serial port */
    serialPort = (SerialPort) mote.getInterfaces().getLog();
    if (serialPort == null) {
      throw new RuntimeException("No mote serial port");
    }
    for (byte b : serialPayload) {
      b = 0;
    }

    logger.info("Listening on port: " + LISTEN_PORT);

    /* Observe serial port for outgoing data */
    serialPort.addSerialDataObserver(
        serialDataObserver =
            new Observer() {
              public void update(Observable obs, Object obj) {
                serialSendFlag = false;
                /* Check the received message to find the moment that message follow the header format
                "0x 00 ff ff 00 00" which is equal to "0 -1 -1 0 0" in decimal. The next byte after
                this message is the message size*/

                lastByte = serialPort.getLastSerialData();
                logger.info("lastByte: " + lastByte);
                if (lastByte == 126 && nRCVedByte < 7) {
                  nRCVedByte = 1;
                  //  messageIndex=0;
                } else if (nRCVedByte > 0 && nRCVedByte < 7) {
                  nRCVedByte++;
                } else if (nRCVedByte == 7) {
                  sizeOfPayload = lastByte;
                  //                    logger.info("sizeOfPayload is: " + sizeOfPayload);
                  nRCVedByte++;
                } else if (nRCVedByte > 7 && nRCVedByte < 10) {
                  nRCVedByte++;
                } else if (nRCVedByte >= 10 && nRCVedByte < 10 + sizeOfPayload) {
                  //                    logger.info("nRCVedByte: " + nRCVedByte);
                  //                    logger.info("messageIndex: " + messageIndex);

                  serialPayload[messageIndex] = lastByte;
                  //                    logger.info("messageIndex: " + messageIndex + "   lastByte:
                  // " + lastByte);
                  if (nRCVedByte == (10 + sizeOfPayload - 1)) {
                    messageIndex = 0;
                    serialSendFlag = true;
                  } else {
                    messageIndex++;
                  }
                  nRCVedByte++;
                } else {
                  nRCVedByte = 0;
                }

                if (serialSendFlag) {

                  simulationTime = (int) sim.getSimulationTimeMillis();
                  serialPinNumber =
                      (skyMote.getID() * 100)
                          + 18; // 18 = pinNumber for Sending data to the serial port in Simulink
                  int u = 0; // value;
                  byte[] serialDataMSG =
                      serialMessageCreator(simulationTime, serialPinNumber, serialPayload);
                  fileWriter(serialPinNumber, serialPayload);
                  int q = serialMsgSender(serialDataMSG, dSocket);
                  serialSendFlag = false;
                  if (serialDataShouldRCV
                      .isSelected()) // If the second scenario has been selected (It should check
                                     // the second scenario CheckBox )
                  {
                    //                        logger.info("Simulation Time is : " +
                    // sim.getSimulationTime());
                    TimeEvent delayedEvent =
                        new TimeEvent(0) {
                          public void execute(long t) {
                            //                                logger.info("  Simulation Time is : "
                            // + sim.getSimulationTime());

                            simulationTime = (int) sim.getSimulationTimeMillis();
                            //                              logger.info("When recoded Simulation
                            // Time is : " + sim.getSimulationTime());
                            serialPinNumber = (skyMote.getID() * 100) + 19; // SerialDataRequest;
                            //                            logger.info("SerialPinNumber is : " +
                            // serialPinNumber);

                            byte[] serialRequestMesg =
                                serialRequestMsgCreator(simulationTime, serialPinNumber);
                            serialRequestSender(serialRequestMesg, dSocket);
                            fileWriter(serialPinNumber, serialRequestMesg);
                          }
                        };

                    sim.scheduleEvent(
                        delayedEvent,
                        sim.getSimulationTime()
                            + (Long.parseLong(CPUDellay.getText()) * (sim.MILLISECOND)));
                  }
                }
              }
            });

    try {
      dSocket = new DatagramSocket(LISTEN_PORT); // (18000 + skyMote.getID());

    } catch (SocketException ex) {
      System.out.println("Errore in dSocket creation");
    }
    IOUnit adc = skyMote.getCPU().getIOUnit("ADC12");
    if (adc instanceof ADC12) {
      ((ADC12) adc).setADCInput(0, new ADCConnector(0));
      ((ADC12) adc).setADCInput(1, new ADCConnector(1));
      ((ADC12) adc).setADCInput(2, new ADCConnector(2));
      ((ADC12) adc).setADCInput(3, new ADCConnector(3));
      ((ADC12) adc).setADCInput(4, new ADCConnector(4));
      ((ADC12) adc).setADCInput(5, new ADCConnector(5));
      ((ADC12) adc).setADCInput(6, new ADCConnector(6));
      ((ADC12) adc).setADCInput(7, new ADCConnector(7));
      ((ADC12) adc).setADCInput(8, new ADCConnector(8));
      ((ADC12) adc).setADCInput(9, new ADCConnector(9));
      ((ADC12) adc).setADCInput(10, new ADCConnector(10));
      ((ADC12) adc).setADCInput(11, new ADCConnector(11));
      ((ADC12) adc).setADCInput(12, new ADCConnector(12));
      ((ADC12) adc).setADCInput(13, new ADCConnector(13));
      ((ADC12) adc).setADCInput(14, new ADCConnector(14));
      ((ADC12) adc).setADCInput(15, new ADCConnector(15));
    }
    ((DAC12) skyMote.getCPU().getIOUnit("DAC12")).setDACOutput(0, new DACConnector(16));
    ((DAC12) skyMote.getCPU().getIOUnit("DAC12")).setDACOutput(1, new DACConnector(17));
  }
예제 #12
0
  public SerialSocketServer(Mote mote, Simulation simulation, final GUI gui) {
    super("Serial Socket (SERVER) (" + mote + ")", gui, false);
    this.mote = mote;

    LISTEN_PORT = 60000 + mote.getID();

    /* GUI components */
    if (GUI.isVisualized()) {
      Box northBox = Box.createHorizontalBox();
      northBox.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
      statusLabel = configureLabel(northBox, "", "");

      Box mainBox = Box.createHorizontalBox();
      mainBox.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
      inLabel = configureLabel(mainBox, "socket -> mote:", "0 bytes");
      outLabel = configureLabel(mainBox, "mote -> socket", "0 bytes");

      getContentPane().add(BorderLayout.NORTH, northBox);
      getContentPane().add(BorderLayout.CENTER, mainBox);
      pack();
    }

    /* Mote serial port */
    serialPort = (SerialPort) mote.getInterfaces().getLog();
    if (serialPort == null) {
      throw new RuntimeException("No mote serial port");
    }

    try {
      logger.info("Listening on port: " + LISTEN_PORT);
      if (GUI.isVisualized()) {
        statusLabel.setText("Listening on port: " + LISTEN_PORT);
      }
      server = new ServerSocket(LISTEN_PORT);
      new Thread() {
        public void run() {
          while (server != null) {
            try {
              client = server.accept();
              in = new DataInputStream(client.getInputStream());
              out = new DataOutputStream(client.getOutputStream());
              out.flush();

              startSocketReadThread(in);
              if (GUI.isVisualized()) {
                statusLabel.setText("Client connected: " + client.getInetAddress());
              }
            } catch (IOException e) {
              logger.fatal("Listening thread shut down: " + e.getMessage());
              server = null;
              cleanupClient();
              break;
            }
          }
        }
      }.start();
    } catch (Exception e) {
      throw (RuntimeException)
          new RuntimeException("Connection error: " + e.getMessage()).initCause(e);
    }

    /* Observe serial port for outgoing data */
    serialPort.addSerialDataObserver(
        serialDataObserver =
            new Observer() {
              public void update(Observable obs, Object obj) {
                try {
                  if (out == null) {
                    /*logger.debug("out is null");*/
                    return;
                  }
                  out.write(serialPort.getLastSerialData());
                  out.flush();
                  outBytes++;
                  if (GUI.isVisualized()) {
                    outLabel.setText(outBytes + " bytes");
                  }
                } catch (IOException e) {
                  cleanupClient();
                }
              }
            });
  }