Ejemplo n.º 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);
            }
          });
    }
  }
  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));
  }
Ejemplo n.º 4
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();
                }
              }
            });
  }