Ejemplo n.º 1
0
  /**
   * Apply the current scaling transformation to the figure.
   *
   * @param figure The figure the transformation is to be applied to.
   * @exception IllegalActionException If the getToken() method throws such an exception.
   */
  protected void _applyTransform(Figure figure) throws IllegalActionException {
    double scaleFactorXValue = 1.0;
    double scaleFactorYValue = 1.0;

    boolean needsTransform = false;

    if ((scaleFactorX.isOutsideConnected()) && scaleFactorX.hasToken(0)) {
      scaleFactorXValue = ((DoubleToken) scaleFactorX.get(0)).doubleValue();
      needsTransform = true;
    }

    if ((scaleFactorY.isOutsideConnected()) && scaleFactorY.hasToken(0)) {
      scaleFactorYValue = ((DoubleToken) scaleFactorY.get(0)).doubleValue();
      needsTransform = true;
    }

    if (needsTransform) {
      if (_isAccumulating()) {
        scaleFactorXValue *= _oldScaleFactorX;
        scaleFactorYValue *= _oldScaleFactorY;
      }

      _oldScaleFactorX = scaleFactorXValue;
      _oldScaleFactorY = scaleFactorYValue;

      AffineTransform inputTransform =
          AffineTransform.getScaleInstance(scaleFactorXValue, scaleFactorYValue);

      figure.transform(inputTransform);
    }
  }
Ejemplo n.º 2
0
  /**
   * If this firing is triggered by an event at <i>waitee</i>, then output the waiting time for each
   * prior event arrival at <i>waiter</i> since the last arrival of waitee. If there is no event at
   * <i>waitee</i>, then record the time of arrival of the events at <i>waiter</i>, and produce no
   * output.
   *
   * @exception IllegalActionException If get() or send() throws it.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    Time currentTime = ((DEDirector) getDirector()).getModelTime();

    while (waiter.hasToken(0)) {
      waiter.get(0);
      _waiting.addElement(currentTime);
    }

    boolean godot = false;

    while (waitee.hasToken(0)) {
      waitee.get(0);
      godot = true;
    }

    if (godot) {
      for (int i = 0; i < _waiting.size(); i++) {
        Time previousTime = (Time) _waiting.elementAt(i);
        DoubleToken outToken = new DoubleToken(currentTime.subtract(previousTime).getDoubleValue());
        output.send(0, outToken);
      }

      _waiting.removeAllElements();
    }
  }
Ejemplo n.º 3
0
  public boolean postfire() throws IllegalActionException {
    switch (_state) {
      case READY:
        {
          if (trigger.hasToken(0) && !shutdown.hasToken(0)) {
            _state = RUNNING;
          }
        }
        break;

      case RUNNING:
        {
          if (shutdown.isKnown()) {
            if (shutdown.hasToken(0)) {
              _reset();
              break;
            }
          }

          if (emstop_input.isKnown()) {
            if (emstop_input.hasToken(0)) {
              _reset();
              break;
            }
          }
        }
        break;
    }

    return true;
  }
Ejemplo n.º 4
0
  /**
   * Return false if either of the input ports has no token, otherwise return what the superclass
   * returns (presumably true).
   *
   * @exception IllegalActionException If there is no director.
   */
  @Override
  public boolean prefire() throws IllegalActionException {
    if (!x.hasToken(0) || !y.hasToken(0)) {
      return false;
    }

    return super.prefire();
  }
Ejemplo n.º 5
0
  /**
   * Does up to three things, in this order: Set new remote address value, Set new remote socket
   * number, transmit data as a UDP packet over the ethernet. The first two can, of course, affect
   * where the datagram goes. Any remote address/socket values supplied are saved and become the
   * defaults for next time.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    String address = null;

    for (int jj = 0; jj < remoteAddress.getWidth(); jj++) {
      if (remoteAddress.hasToken(jj)) {
        address = ((StringToken) (remoteAddress.get(jj))).stringValue();
      }
    }

    if (address != null) {
      try {
        _address = InetAddress.getByName(address);
      } catch (UnknownHostException ex) {
        throw new IllegalActionException(
            this, ex, "The input remote " + "address specifies an unknown host");
      }
    }

    for (int jj = 0; jj < remoteSocketNumber.getWidth(); jj++) {
      if (remoteSocketNumber.hasToken(jj)) {
        // Valid socket numbers are 0..65535,
        // so keep only lower 16 bits.
        _remoteSocketNumber = 65535 & ((IntToken) remoteSocketNumber.get(jj)).intValue();
      }
    }

    if (data.hasToken(0)) {
      ArrayToken dataArrayToken = (ArrayToken) data.get(0);

      byte[] dataBytes = new byte[dataArrayToken.length()];

      for (int j = 0; j < dataArrayToken.length(); j++) {
        UnsignedByteToken token = (UnsignedByteToken) dataArrayToken.getElement(j);
        dataBytes[j] = token.byteValue();
      }

      DatagramPacket packet =
          new DatagramPacket(dataBytes, dataBytes.length, _address, _remoteSocketNumber);

      try {
        _socket.send(packet);
      } catch (IOException ex) {
        // ignore, UDP does not guarantee success
        // throw new InternalErrorException("socket.send failed");
        // FIXME  I don't believe that!  I think send guarantees that
        // it will send!!  Just not that anyone is listening.
        //    (yet when I ran it with 'throw...' uncommented
        //     then it threw it right away!? )
        // Would TCP stall here awaiting reply??  I doubt it!
      }

      triggerOutput.broadcast(new Token());
    }
  }
Ejemplo n.º 6
0
  public void fire() throws IllegalActionException {
    super.fire();

    try {
      if (trigQuery.hasToken(0)) {
        trigQuery.get(0);

        System.out.println("Send peer discovery message...");

        // send a query message that is
        // - propagated within the group
        // - for peer discovery
        // - no attribute/value matching
        // - each response contains at most 5 peers
        _discoveryService.getRemoteAdvertisements(null, DiscoveryService.PEER, null, null, 5);

        System.out.println("Send actor query message...");
        _actorQueryMessage.setQueryId(_actorQueryMessage.getQueryId() + 1);
        _resolverService.sendQuery(null, _actorQueryMessage);
      }

      if (_inToken != null) {
        queryResult.send(0, _inToken);
        _inToken = null;
        System.out.println("send data ");
      }
    } catch (Exception e) {
      System.out.println("Error : " + e);
    }
  }
Ejemplo n.º 7
0
  /**
   * Read one RecordToken from the input port and send its fields to the output ports. If the input
   * does not have a token, suspend firing and return.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    Director director = getDirector();

    if (director == null) {
      throw new IllegalActionException(this, "No director!");
    }

    if (input.hasToken(0)) {
      RecordToken record = (RecordToken) input.get(0);
      Iterator labels = record.labelSet().iterator();

      while (labels.hasNext()) {
        String label = (String) labels.next();
        Token value = record.get(label);
        IOPort port = (IOPort) getPort(label);

        // since the record received may contain more fields than the
        // output ports, some fields may not have a corresponding
        // output port.
        if (port != null) {
          port.send(0, value);
        }
      }
    }
  }
Ejemplo n.º 8
0
  /**
   * Read a token from each input port. If the token from the <i>control</i> input is true, then
   * output the token consumed from the <i>input</i> port on the <i>trueOutput</i> port, otherwise
   * output the token on the <i>falseOutput</i> port.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    if (control.hasToken(0)) {
      _control = ((BooleanToken) control.get(0)).booleanValue();
    }

    if (input.hasToken(0)) {
      Token token = input.get(0);

      if (_control) {
        trueOutput.send(0, token);
      } else {
        falseOutput.send(0, token);
      }
    }
  }
Ejemplo n.º 9
0
  /**
   * If there is at least one token on the input ports, multiply tokens from the <i>multiply</i>
   * port, divide by tokens from the <i>divide</i> port, and send the result to the output port. At
   * most one token is read from each channel, so if more than one token is pending, the rest are
   * left for future firings. If none of the input channels has a token, do nothing. If none of the
   * multiply channels have tokens, then the tokens on the divide channels are divided into a one
   * token of the same type as the denominator.
   *
   * @exception IllegalActionException If there is no director, or if multiplication and division
   *     are not supported by the available tokens.
   */
  @Override
  public void fire() throws IllegalActionException {
    super.fire();
    Token numerator = null;
    try {
      for (int i = 0; i < multiply.getWidth(); i++) {
        if (multiply.hasToken(i)) {
          if (numerator == null) {
            numerator = multiply.get(i);
          } else {
            numerator = numerator.multiply(multiply.get(i));
          }
        }
      }

      Token denominator = null;

      for (int i = 0; i < divide.getWidth(); i++) {
        if (divide.hasToken(i)) {
          if (denominator == null) {
            denominator = divide.get(i);
          } else {
            denominator = denominator.multiply(divide.get(i));
          }
        }
      }

      if (numerator == null) {
        if (denominator == null) {
          return;
        }

        // For the benefit of copernicus, this means that
        // numerator always has the same type.
        numerator = multiply.getType().convert(denominator.one());
      }

      if (denominator != null) {
        numerator = numerator.divide(denominator);
      }
    } catch (Exception e) {
      throw new IllegalActionException(this, e.getCause(), e.getMessage());
    }

    output.send(0, numerator);
  }
Ejemplo n.º 10
0
  public void fire() throws IllegalActionException {

    // reads all queue updates
    for (int i = 0; i < nqueues; i++) {

      if (queueUpdate.hasToken(i)) {

        IntToken queuedTasks = (IntToken) queueUpdate.get(i);
        queues[i] = queuedTasks.intValue();
      }
    }

    // sends new task, if any, to the queue with the shortest queue
    if (input.hasToken(0)) {

      output.send(this.getShortestQueue(), input.get(0));
    }
  }
Ejemplo n.º 11
0
  /**
   * Send the token in the input to the output.
   *
   * @exception IllegalActionException If it is thrown by the send() method sending out the token.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    Token sum = null;
    if (input.hasToken(0)) {
      sum = input.get(0);
    }

    for (int i = 0; i < multiportInput.getWidth(); i++) {
      if (multiportInput.hasToken(i)) {
        if (sum == null) {
          sum = multiportInput.get(i);
        } else {
          sum = sum.add(multiportInput.get(i));
        }
      }
    }
    if (sum != null) {
      output.send(0, sum);
    }
  }
Ejemplo n.º 12
0
  /**
   * If the <i>enable</i> input is connected, then if it has a true token, produce the next output.
   * If it is not connected, produce the next output unconditionally. Whether it is connected is
   * determined by checking the width of the port.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    if ((!enable.isOutsideConnected())
        || (enable.hasToken(0) && ((BooleanToken) enable.get(0)).booleanValue())) {
      ArrayToken valuesArray = (ArrayToken) values.getToken();

      if (_currentIndex < valuesArray.length()) {
        output.send(0, valuesArray.getElement(_currentIndex));
        _outputProduced = true;
      }
    }
  }
Ejemplo n.º 13
0
  /**
   * Consumes packet header Consumes clock token Checks for buffers requesting arbitration
   *
   * @exception IllegalActionException If there is no director.
   */
  public boolean prefire() throws IllegalActionException {
    super.prefire();

    // reads clock signal, if available

    if (wakeup.hasToken(0)) {
      wakeup.get(0);
      clocked = true;
    }

    return true;
  }
Ejemplo n.º 14
0
  /**
   * Read the search parameter, if it matches "Search 50" then we've "got" data. Let the Loop Actor
   * know it can stop searching
   */
  public void fire() throws IllegalActionException {
    super.fire();

    if (search.getWidth() > 0 && search.hasToken(0)) {
      String searchStr = ((StringToken) search.get(0)).stringValue();
      if (searchStr.equals("Search 50")) {
        System.out.println("Found DATA!");
        resultsOutput.broadcast(new StringToken("Results Found"));

      } else {
        System.out.println("Didn't Match! " + searchStr);
        resultsOutput.broadcast(new StringToken("No Data"));
      }
    }
  }
Ejemplo n.º 15
0
  /**
   * Add the key to the keystore.
   *
   * @exception IllegalActionException If there's no director, if there are problems setting the
   *     key.
   */
  public boolean postfire() throws IllegalActionException {
    // See io.LineWriter for an example of an actor that writes to a file.
    if (input.hasToken(0)) {
      KeyToken keyToken = (KeyToken) input.get(0);
      java.security.Key key = keyToken.getValue();

      if (key instanceof java.security.PrivateKey) {
        throw new IllegalActionException(
            this,
            "Key is a PrivateKey, which is not supported because " + "it requires a certificate");
      }

      // Now we add the key to the keystore, protected
      // by the password.
      try {
        _keyStore.setKeyEntry(_alias, key, _keyPassword.toCharArray(), null /* No certificate */);
      } catch (Exception ex) {
        throw new IllegalActionException(
            this, ex, "Failed to set key '" + key + "' to alias '" + alias + "'");
      }

      try {
        FileOutputStream keyStoreOutputStream = null;

        try {
          keyStoreOutputStream = new FileOutputStream(fileOrURL.asFile());
          _keyStore.store(keyStoreOutputStream, _storePassword.toCharArray());
          keyStoreOutputStream.close();
        } finally {
          try {
            if (keyStoreOutputStream != null) {
              keyStoreOutputStream.close();
            }
          } catch (Throwable throwable) {
            System.out.println("Ignoring failure to close stream " + "on " + fileOrURL.asFile());
            throwable.printStackTrace();
          }
        }

        output.broadcast(BooleanToken.TRUE);
      } catch (Throwable throwable) {
        throw new IllegalActionException(
            this, throwable, "Failed to store " + fileOrURLDescription());
      }
    }

    return super.postfire();
  }
Ejemplo n.º 16
0
 /**
  * If the <i>enable</i> input is not known, then return false; if the <i>enable</i> input is known
  * and either absent or false, then also return false; if it is known and true, then invoke the
  * prefire() method of the superclass and return what it returns.
  *
  * @exception IllegalActionException If the superclass throws it.
  */
 public boolean prefire() throws IllegalActionException {
   boolean prefireReturnValue = false;
   if (enable.isKnown(0)) {
     if (enable.hasToken(0)) {
       prefireReturnValue = ((BooleanToken) enable.get(0)).booleanValue();
       if (prefireReturnValue) {
         // This will call prefire() on the contained director.
         prefireReturnValue = super.prefire();
       }
     }
   }
   if (_debugging) {
     _debug("EnabledComposite: prefire() returns " + prefireReturnValue);
   }
   return prefireReturnValue;
 }
Ejemplo n.º 17
0
  /**
   * If there is no input on the <i>trigger</i> port, return false, indicating that this actor does
   * not want to fire. This has the effect of leaving input values in the input ports, if there are
   * any.
   *
   * @exception IllegalActionException If there is no director.
   */
  public boolean prefire() throws IllegalActionException {

    boolean hasReadTrigger = false;

    if (read.getWidth() > 0) {
      hasReadTrigger = (read.hasToken(0));
    }

    // if read notification is received, remove the oldest token
    // from the queue
    if (hasReadTrigger) {
      // Consume the trigger token.
      read.get(0);
      _queue.take();
    }

    return true;
  }
Ejemplo n.º 18
0
  // NOTE: No clone() method, so don't clone this.
  public void fire() throws IllegalActionException {
    super.fire();
    double increment = 0.0;

    if ((input.getWidth() > 0) && input.hasToken(0)) {
      DoubleToken in = (DoubleToken) input.get(0);
      increment = in.doubleValue();
    }

    output.broadcast(new DoubleToken(value + increment));
    value += 1.0;

    Director director = getDirector();
    Time time = director.getModelTime();
    count++;

    if (count >= 5) {
      director.fireAt(this, time.add(1.0));
      count = 0;
    } else {
      director.fireAt(this, time);
    }
  }
Ejemplo n.º 19
0
  /**
   * Read at most one token from the input port and issue a change request to update variables as
   * indicated by the input.
   *
   * @exception IllegalActionException If thrown reading the input.
   */
  public boolean postfire() throws IllegalActionException {
    if (input.hasToken(0)) {
      final Token value = input.get(0);

      if (delayed.getToken().equals(BooleanToken.TRUE)) {
        ChangeRequest request =
            new ChangeRequest(this, "SetVariable change request") {
              protected void _execute() throws IllegalActionException {
                _setValue(value);
              }
            };

        // To prevent prompting for saving the model, mark this
        // change as non-persistent.
        request.setPersistent(false);
        request.addChangeListener(this);
        requestChange(request);
      } else {
        _setValue(value);
      }
    }

    return true;
  }
Ejemplo n.º 20
0
 @Override
 public void fire() throws IllegalActionException {
   // Process each task
   while (input.hasToken(0)) dispatchTask((RecordToken) input.get(0));
 }
Ejemplo n.º 21
0
  /**
   * Read the argument of the function from the ports, call the native method throw the generated
   * interface, and put the results on the corresponding ports.
   *
   * @exception IllegalActionException If a exception occured
   */
  public void fire() throws IllegalActionException {
    super.fire();
    // getting the in/inout parameters
    Iterator ports = this.portList().iterator();
    Vector args = new Vector();

    while (ports.hasNext()) {
      TypedIOPort port = (TypedIOPort) ports.next();

      if (port.isInput() && port.hasToken(0) && !(port.isOutput() && !port.isInput())) {
        Token tok = port.get(0);

        String typ = _methods[_methodIndex].getParameterTypes()[args.size()].toString();

        if (typ.equals("boolean")) {
          args.add(Boolean.valueOf(((BooleanToken) tok).booleanValue()));
        } else if (typ.equals("int")) {
          args.add(Integer.valueOf(((IntToken) tok).intValue()));
        } else if (typ.equals("long")) {
          args.add(Long.valueOf(((ScalarToken) tok).longValue()));
        } else if (typ.equals("double")) {
          args.add(Double.valueOf(((DoubleToken) tok).doubleValue()));
        } else if (typ.equals("class [I")) {
          int siz = ((ArrayToken) tok).arrayValue().length;
          int[] tab = new int[siz];

          for (int j = 0; j < siz; j++) {
            tab[j] = ((IntToken) (((ArrayToken) tok).arrayValue()[j])).intValue();
          }

          // (int[])((ArrayToken)tok).arrayValue();
          args.add(tab);
        } else if (typ.equals("class [J")) {
          int siz = ((ArrayToken) tok).length();
          long[] tab = new long[siz];

          for (int j = 0; j < siz; j++) {
            Token element = ((ArrayToken) tok).getElement(j);
            try {
              tab[j] = ((LongToken) element).longValue();
            } catch (Throwable throwable) {
              throw new IllegalActionException(
                  this,
                  throwable,
                  "Failed to create LongToken, element "
                      + j
                      + " was: "
                      + element.getClass().getName()
                      + ", value: "
                      + element
                      + ", port: "
                      + port);
            }
          }

          // (int[])((ArrayToken)tok).arrayValue();
          args.add(tab);
        } else {
          System.out.println(
              "The intype \"" + typ + "\" is not convertible " + "with Ptolemy II types.");
        }
      }
    }

    // tBFixed : the out parameter is not in by definition
    // ...so no port in can initialize the param
    // call the native function
    Object obj = null;
    Object ret = null;

    try {
      try {
        obj = _class.newInstance();
      } catch (Error error) {
        // Using JNI to link in a native library
        // can result in a java.lang.UnsatisfiedLinkError
        // which extends Error, not Exception.
        // FIXME: Rethrow the error as an exception
        String libraryPath = StringUtilities.getProperty("java.library.path");

        throw new Exception(
            "Class '"
                + _class
                + "' cannot be instantiated.\n"
                + "If you are running under Windows, "
                + "be sure that the directory containing the library "
                + "is in your PATH.\n"
                + "If you are running under Solaris, "
                + "be sure that the directory containing the library "
                + "is in your LD_LIBRARY_PATH and that the library "
                + "name begin with 'lib' and end with '.so'.\n"
                + "You may need to exit, set your "
                + "PATH or LD_LIBRARY_PATH to include the directory "
                + "that contains the shared library and "
                + "restart.\n"
                + "For example, under Windows "
                + "in a Cygwin bash shell:\n"
                + "PATH=/cygdrive/c/ptII/jni/dll:${PATH}\n"
                + "export PATH\n"
                + "vergil -jni foo.xml\n"
                + "A common error is that "
                + "the class cannot be found in "
                + "property 'java.library.path' "
                + "which is:\n"
                + libraryPath
                + "\nError message was: "
                + error.getMessage(),
            error);
      }
    } catch (Exception ex) {
      throw new IllegalActionException(this, ex, "Class cannot be instantiated");
    }

    try {
      ret = _methods[_methodIndex].invoke(obj, args.toArray());
    } catch (Throwable ex) {
      StringBuffer argumentsDescription = new StringBuffer("");

      try {
        if (args.size() >= 1) {
          argumentsDescription.append(args.elementAt(0).toString());

          for (int i = 1; i < args.size(); i++) {
            argumentsDescription.append(", " + args.elementAt(i).toString());
          }
        }
      } catch (Throwable throwable) {
        // Ignore
      }

      throw new IllegalActionException(
          this,
          ex,
          "Native operation call failed."
              + "Failed to invoke '"
              + obj
              + "' with "
              + args.size()
              + " arg(s) "
              + argumentsDescription.toString());
    }

    ports = portList().iterator();

    while (ports.hasNext()) {
      TypedIOPort port = (TypedIOPort) ports.next();

      // if the argument is return
      if (getArgumentReturn() == null) {
        System.err.println("Warning: GenericJNIActor.java: " + "getArgumentReturn() returns null?");
      }

      if ((port != null)
          && (port.getName() != null)
          && (getArgumentReturn() != null)
          && port.getName().equals(this.getArgumentReturn().getName())) {
        String typ = "";
        Field field = null;

        try {
          field = _class.getDeclaredField("_" + port.getName());
          typ = field.getType().toString();
        } catch (NoSuchFieldException e) {
          try {
            throw new IllegalActionException(
                this, e, "No return type field '_" + port.getName() + "'");
          } catch (Throwable throwable) {
            getDirector().stop();
          }
        }

        if (typ.equals("boolean")) {
          port.send(0, new BooleanToken(((Boolean) ret).booleanValue()));
        } else if (typ.equals("double")) {
          port.send(0, new DoubleToken(((Double) ret).doubleValue()));
        } else if (typ.equals("int")) {
          port.send(0, new IntToken(((Integer) ret).intValue()));
        } else if (typ.equals("long")) {
          port.send(0, new LongToken(((Long) ret).longValue()));
        } else if (typ.equals("char")) {
          port.send(0, new UnsignedByteToken(((Byte) ret).byteValue()));
        } else {
          System.out.println("The return type is not convertible " + "with Ptolemy II types.");
        }
      }
      // if the argument is output
      else if ((port != null)
          && port.isOutput()
          && (port.getName() != null)
          && (getArgumentReturn() != null)
          && !(port.getName().equals(this.getArgumentReturn().getName()))) {
        String typ = "";
        Field field = null;

        try {
          field = _class.getDeclaredField("_" + port.getName());
          typ = field.getType().toString();
        } catch (NoSuchFieldException ex) {
          try {
            field =
                _class.getDeclaredField(
                    "_" + port.getName().substring(0, port.getName().length() - 3));
            typ = field.getType().toString();
          } catch (Throwable throwable) {
            try {
              throw new IllegalActionException(
                  this, throwable, "No '+" + port.getName() + "' field !");
            } catch (Throwable throwable2) {
              getDirector().stop();
            }
          }
        }

        if (field == null) {
          throw new InternalErrorException(
              "Field '" + port.getName() + "' in '" + _class + "' is null?");
        } else {
          if (typ.equals("boolean")) {
            try {
              port.send(0, new BooleanToken(field.getBoolean(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("double")) {
            try {
              port.send(0, new DoubleToken(field.getDouble(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("int")) {
            try {
              port.send(0, new IntToken(field.getInt(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("long")) {
            try {
              port.send(0, new LongToken(field.getLong(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("char")) {
            try {
              port.send(0, new UnsignedByteToken(field.getChar(obj)));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("class [I")) {
            try {
              if (obj == null) {
                throw new InternalErrorException("obj == null?");
              }
              if (field.get(obj) == null) {
                throw new InternalErrorException(
                    "field.get(obj)  == null? (field = " + field + " obj = " + obj);
              }
              Token[] toks = new Token[((int[]) field.get(obj)).length];

              for (int j = 0; j < ((int[]) field.get(obj)).length; j++) {
                toks[j] = new IntToken(((int[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(BaseType.INT, toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else if (typ.equals("class [J")) {
            Token[] toks = null;
            try {
              if (obj == null) {
                throw new InternalErrorException("obj == null?");
              }
              if (field.get(obj) == null) {
                throw new InternalErrorException(
                    "field.get(obj)  == null? (field = " + field + " obj = " + obj);
              }
              toks = new Token[((long[]) field.get(obj)).length];

              for (int j = 0; j < ((long[]) field.get(obj)).length; j++) {
                toks[j] = new LongToken(((long[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(BaseType.LONG, toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            } catch (IllegalActionException ex2) {
              throw new IllegalActionException(
                  this,
                  ex2,
                  "Failed to send a Long array token "
                      + (toks == null ? "null" : toks.length)
                      + " to "
                      + port);
            }
          } else if (typ.equals("class [D")) {
            try {
              Token[] toks = new Token[((double[]) field.get(obj)).length];

              for (int j = 0; j < ((double[]) field.get(obj)).length; j++) {
                toks[j] = new DoubleToken(((double[]) field.get(obj))[j]);
              }

              port.send(0, new ArrayToken(toks));
            } catch (IllegalAccessException ex) {
              throw new IllegalActionException(this, ex, "Type '" + typ + "' is not castable");
            }
          } else {
            // FIXME: for char[] and boolean[], there is
            // no corresponding Token type.
            System.out.println(
                "The outtype '" + typ + "' is not convertible " + "with Ptolemy II types.");
          }
        }
      }
    }
  }
Ejemplo n.º 22
0
  /**
   * If a new message is available at the inputs, record it in the list indexed with the time that
   * the message shall be completed, and loop through the list to check whether there is collision.
   * If the current time matches one of the times that we have previously recorded as the completion
   * time for a transmission, then output the received message to the <i>received</i> output port if
   * it is not lost to a collision; otherwise, output it to the <i>collided</i> output port.
   *
   * @exception IllegalActionException If an error occurs reading or writing inputs or outputs.
   */
  public void fire() throws IllegalActionException {
    super.fire();

    Time currentTime = getDirector().getModelTime();

    if (_debugging) {
      _debug("---------------------------------");
      _debug("Current time is: " + currentTime);
    }

    if (message.hasToken(0) && power.hasToken(0) && duration.hasToken(0)) {
      double powerValue = ((DoubleToken) power.get(0)).doubleValue();

      if (_debugging) {
        _debug("Received message with power: " + powerValue);
      }

      if (powerValue < _powerThreshold) {
        // The signal it too weak to be detected, simply drop it.
        message.get(0);
        duration.get(0);

        if (_debugging) {
          _debug("Message power is below threshold. Ignoring.");
        }
      } else {
        // Record the reception.
        Reception reception = new Reception();
        reception.data = message.get(0);
        reception.power = powerValue;
        reception.arrivalTime = currentTime.getDoubleValue();
        reception.collided = false;
        reception.duration = ((DoubleToken) duration.get(0)).doubleValue();

        if (_debugging) {
          _debug("Message is above threshold and has duration: " + reception.duration);
        }

        // Update the total power density.
        _totalPower = _totalPower + reception.power;

        // Put the new reception into the list of prior receptions.
        Time time = currentTime.add(reception.duration);
        reception.expiration = time.getDoubleValue();

        _receptions.add(reception);

        // Schedule this actor to be fired at the end of
        // the duration of the message.
        _fireAt(time);
      }
    }

    // Loop through the prior receptions (and the new one)
    // to mark whether a message is collided according to the new total
    // power density. Also, any prior receptions that are now
    // expiring are sent to one of the two outputs.
    Iterator priorReceptions = _receptions.listIterator();

    while (priorReceptions.hasNext()) {
      Reception priorReception = (Reception) priorReceptions.next();

      if (_debugging) {
        _debug("Checking reception with arrival time: " + priorReception.arrivalTime);
      }

      // If the reception is now expiring, send it to one of the two
      // output ports.
      if (priorReception.expiration == currentTime.getDoubleValue()) {
        if (_debugging) {
          _debug(
              "Current time matches expiration "
                  + "time of a prior message that arrived at: "
                  + priorReception.arrivalTime);
        }

        // The time matches a pending reception.
        priorReceptions.remove();

        // Update the total power.
        _totalPower = _totalPower - priorReception.power;

        // Quantization errors may take this negative. Do not allow.
        if (_totalPower < 0.0) {
          _totalPower = 0.0;
        }

        if (!priorReception.collided) {
          received.send(0, priorReception.data);

          if (_debugging) {
            _debug("Message has been received: " + priorReception.data);
          }
        } else {
          collided.send(0, priorReception.data);

          if (_debugging) {
            _debug("Message has been lost: " + priorReception.data);
          }
        }

        continue;
      }

      // Check the snr to see whether to mark this prior reception
      // collided.
      double powerWithoutThisOne = _totalPower - priorReception.power;

      // Quantization errors may make this negative.
      if (powerWithoutThisOne < 0.0) {
        powerWithoutThisOne = 0.0;
      }

      double snr = priorReception.power / powerWithoutThisOne;

      if (!priorReception.collided && (snr <= _SNRThresholdInDB)) {
        priorReception.collided = true;

        if (_debugging) {
          _debug(
              "Message now has a collision. SNR is: " + snr + ". Total power is: " + _totalPower);
        }
      }
    }
  }
Ejemplo n.º 23
0
  public void fire() throws IllegalActionException {
    Time currentTime =
        getDirector().getModelTime(); // Get the model time to be used for various calculations

    if (changeChan) { // Check if we need to change the channel in this fire period
      setChannel(nextChannel); // Change to the next required channel
      changeChan = false; // Return to normal operation upon the next fire
      if (input.hasToken(
          0)) { // If this fire was initiated by a token on the input, consume it to avoid loops
        input.get(0);
      }
    } else if (input.hasToken(0)) { // Wireless token has been received f
      SinkData channel =
          channelStore.get(currentChannel); // Retrieve the information for the current channel
      switch (channel.state) { // Determine what stage of the system we are at
        case FIRSTRX: // Stage one, we will be receiving the first synchronisation packet
          handleFirstRX(channel, currentTime);
          break;
        case SECONDRX: // Stage two, we will be receiving the second synchronisation packet
          handleSecondRX(channel, currentTime);
          break;
        case NCALC: // Stage 4, we will be receiving the first synchronisation packet of the
                    // sequence to ascertain the n value
          handleNCalc(channel, currentTime);
          break;
        default: // We are in a state that does not require an input token, so we discard it
          input.get(0);
          break;
      }
    } else { // No token has been received so it is a fire initiated by the source and not a token
             // on the input
      SinkData channel = null; // Initialise a channel to be used later
      int desiredChannelNum =
          currentChannel; // Initialise a variable to store the channel required for this firing
      for (int channelNum :
          channelStore
              .keySet()) { // We need to find the channel that has caused the actor to be fired in
                           // this time period
        channel =
            channelStore.get(channelNum); // Retrieve the information for the channel being checked
        if (channel.nextFireTime != null
            && channel.state
                != states.FINISHED) { // If we have a valid firing time, that has been initialised
          if (!channel.nextFireTime.equals(
              currentTime)) { // We are on an incorrect channel, continue searching
            continue;
          } else { // We have found the correct channel
            desiredChannelNum = channelNum; // Set the desired channel to the channel we have found
            break;
          }
        }
      }
      if (currentChannel == desiredChannelNum) { // If we are on the channel that we desire
        System.out.println(
            channel.nextFireTime.getDoubleValue() <= currentTime.getDoubleValue() + 0.4);
        if (channel.nextFireTime.getDoubleValue()
            <= currentTime.getDoubleValue() + 0.4) { // If we are not too early for the firing time
          switch (channel.state) { // Determine what stage of the system we are at
            case FIRSTTX: // Stage 3, we are in the receive period for the channels sink so we can
                          // transmit a packet
              handleFirstTX(channel, currentTime);
              changeChan = true; // Change back to the channel back to what we had previously
              getDirector().fireAt(this, currentTime.add(0.000001));
              break;
            case SECONDTX: // Stage 5, we are in the receive period for the second time, so we can
                           // transmit a packet
              handleSecondTX(channel, currentTime);
              changeChan = true; // Change back to the channel back to what we had previously
              getDirector().fireAt(this, currentTime.add(0.000001));
              break;
          }
        }
      } else if (desiredChannelNum
          != 0) { // We are not on the desired channel, so we have to change to it
        //		System.out.println(currentChannel + " : " + desiredChannelNum);
        nextChannel =
            currentChannel; // Set the channel we will change back to after the transmit to our
                            // current channel
        setChannel(desiredChannelNum); // Set the channel to the desired channel
        channel.nextFireTime =
            currentTime.add(
                0.0000001); // Set the channels fire time to when we are firing it so we can detect
                            // which channel fired
        getDirector()
            .fireAt(
                this,
                currentTime.add(0.0000001)); // Fire the actor again so we can process the transmit
      }
    }
  }
Ejemplo n.º 24
0
  /**
   * State machine responsable by receiving the traffic from the input port, disassembly the package
   * and send its flits to the output ports (file). If the input does not have a token, suspend
   * firing and return.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    accept = BooleanToken.FALSE;

    // **************Receiving file**************************** //
    if (state == RECEIVING_ADD) {
      if (data_in.hasToken(0)) {

        cont = 0;
        // get the timestamp of the first flit received from the NoC
        timestamp_ff = (int) getDirector().getCurrentTime();
        // timestap_f_flit = timestamp_ff;

        // get the xy adress
        record = ((RecordToken) data_in.get(0));
        x = ((IntToken) record.get("x")).intValue();
        y = ((IntToken) record.get("y")).intValue();
        s_xy = (Integer.toString(x)) + (Integer.toString(y));
        for (int i = s_xy.length(); i < 4; i++) s_xy = "0" + s_xy;

        printFlit(s_xy);

        debug.send(
            0,
            new StringToken("RECEIVING_ADD " + s_xy + " AT TIME: " + getDirector().getModelTime()));

        // set new state
        state = RECEIVING_SIZE;
      } else {
        state = RECEIVING_ADD;
      }
    } // end if RECEIVING_ADD

    if (state == RECEIVING_SIZE) {

      if (data_in.hasToken(0)) {

        record = ((RecordToken) data_in.get(0));
        size = ((IntToken) record.get("size")).intValue();
        size_s = (Integer.toHexString(size).toUpperCase());
        for (int i = size_s.length(); i < 4; i++) size_s = "0" + size_s;
        cont++;
        printFlit(size_s);

        debug.send(
            0,
            new StringToken(
                "RECEIVING_SIZE " + size + " AT TIME: " + getDirector().getModelTime()));
        state = SENDING;
        cont = 0;
      } else {
        state = RECEIVING_SIZE;
      }
    } // end if RECEIVING_ADD
    else if (state == SENDING) {
      debug.send(0, new StringToken("SENDING "));
      if (data_in.hasToken(0)) {
        record = ((RecordToken) data_in.get(0));
        payload = ((IntToken) record.get("payload")).intValue();
        payload_s = (Integer.toHexString(payload).toUpperCase());
        for (int i = payload_s.length(); i < 4; i++) payload_s = "0" + payload_s;

        cont++;
        if (cont != size) {
          debug.send(
              0,
              new StringToken(
                  "payload_s " + payload + " AT TIME: " + getDirector().getModelTime()));
          printFlit(payload_s);
          state = SENDING;
        } else {
          printFlit(payload_s);
          timestamp_ini = ((IntToken) record.get("timestamp_ini")).intValue();
          timestamp_rede = ((IntToken) record.get("timestamp_sent")).intValue();

          // timestamp of the last flit of the packet
          timestamp_lf = (int) getDirector().getCurrentTime();

          int latency = timestamp_lf - timestamp_rede;

          double ini_simulation_time = ((DoubleToken) record.get("simulation_time")).doubleValue();
          double simu = (new java.util.Date()).getTime();
          simulation_time = (int) ((simu - ini_simulation_time) / 1000);

          debug.send(0, new StringToken("foi "));

          data_out.send(
              0,
              new StringToken(
                  readOutput_file()
                      + timestamp_ini
                      + " "
                      + timestamp_rede
                      + " "
                      + timestamp_lf
                      + " "
                      + latency
                      + " "
                      + simulation_time));
          state = RECEIVING_ADD;
          // wrapup();
        }
      } else {
        state = SENDING;
      }
    }
  } // end public
Ejemplo n.º 25
0
  /**
   * Consume at most one array from the input ports and produce the index of the first bin that
   * breaks the threshold.
   *
   * @exception IllegalActionException If there is no director.
   */
  public void fire() throws IllegalActionException {
    super.fire();
    start.update();

    if (array.hasToken(0)) {
      ArrayToken inputArray = (ArrayToken) array.get(0);
      int inputSize = inputArray.length();

      int startValue = ((IntToken) start.getToken()).intValue();

      if ((startValue >= inputSize) || (startValue < 0)) {
        throw new IllegalActionException(this, "start is out of range: " + startValue);
      }

      int increment = -1;

      if (((BooleanToken) forwards.getToken()).booleanValue()) {
        increment = 1;
      }

      double reference = ((DoubleToken) inputArray.getElement(startValue)).doubleValue();

      double thresholdValue = ((DoubleToken) threshold.getToken()).doubleValue();

      String scaleValue = scale.stringValue();

      boolean aboveValue = ((BooleanToken) above.getToken()).booleanValue();

      if (scaleValue.equals("relative amplitude decibels")) {
        if (aboveValue) {
          thresholdValue = reference * Math.pow(10.0, (thresholdValue / 20));
        } else {
          thresholdValue = reference * Math.pow(10.0, (-thresholdValue / 20));
        }
      } else if (scaleValue.equals("relative power decibels")) {
        if (aboveValue) {
          thresholdValue = reference * Math.pow(10.0, (thresholdValue / 10));
        } else {
          thresholdValue = reference * Math.pow(10.0, (-thresholdValue / 10));
        }
      } else if (scaleValue.equals("relative linear")) {
        if (aboveValue) {
          thresholdValue = reference + thresholdValue;
        } else {
          thresholdValue = reference - thresholdValue;
        }
      }

      // Default output if we don't find a crossing.
      int bin = -1;

      for (int i = startValue; (i < inputSize) && (i >= 0); i += increment) {
        double currentValue = ((DoubleToken) inputArray.getElement(i)).doubleValue();

        if (aboveValue) {
          // Searching for values above the threshold.
          if (currentValue > thresholdValue) {
            bin = i;
            break;
          }
        } else {
          // Searching for values below the threshold.
          if (currentValue < thresholdValue) {
            bin = i;
            break;
          }
        }
      }

      output.send(0, new IntToken(bin));
    }
  }
Ejemplo n.º 26
0
  public void fire() throws IllegalActionException {

    if (_state == RUNNING) {
      if (alfa.isKnown() && !emmode.isKnown()) {
        // if(alfa.isKnown()) {
        if (alfa.hasToken(0)) {
          double _alfa = ((DoubleToken) alfa.get(0)).doubleValue();

          /*
          if(_count > 0) {   // so atualiza se um evento true deu inicio
              _count++;
          }*/

          if (Math.abs(_alfa) >= 0.10) { // tem um evento
            // _sensorCount++;
            // if(_count == 0) {
            //    _count = 1;
            // }
            _count++;
          } else {
            _count = 0;
          }

          if (_count == 25) {
            emmode.broadcast(new Token());
            System.out.println("Entering Emergency Mode");
            _reset(); // uma vez setado o emmode, so na proxima....
          }

          /*
          if(_count == 50) {   // deu os 100ms
              if(_maxSensorCount >= 25 ||
                 _sensorCount >= 25) {
                  emmode.broadcast(new Token());
                  System.out.println("Entering Emergency Mode");

                  _reset(); // uma vez setado o emmode, so na proxima....
              }
              else {
                  _count = 0;
                  _sensorCount = 0;
                  _maxSensorCount = 0;
              }
          }
          else {
              if(Math.abs(_alfa) >= 0.10) {      // tem um evento
                  _sensorCount++;
                  if(_count == 0) {
                      _count = 1;
                  }
              }
              if((Math.abs(_alfa) < 0.1) && _count > 0) {    // nao tem mais , e estava contando
                  if(_sensorCount > _maxSensorCount) {
                      _maxSensorCount = _sensorCount;
                  }
                  _sensorCount = 0;
              }
          } */
        }
      }
    }

    if (alfa.isKnown() && !emmode.isKnown()) {
      emmode.broadcastClear();
    }
  }
Ejemplo n.º 27
0
  /**
   * If the value at the <i>derivative</i> port is known, and the current step size is bigger than
   * 0, perform an integration. If the <i>impulse</i> port is known and has data, then add the value
   * provided to the state; if the <i>initialState</i> port is known and has data, then reset the
   * state to the provided value. If both <i>impulse</i> and <i>initialState</i> have data, then
   * <i>initialState</i> dominates. If either is unknown, then simply return, leaving the output
   * unknown. Note that the signals provided at these two ports are required to be purely discrete.
   * This is enforced by throwing an exception if the current microstep is zero when they have input
   * data.
   *
   * @exception IllegalActionException If the input is infinite or not a number, or if thrown by the
   *     solver, or if data is present at either <i>impulse</i> or <i>initialState</i> and the step
   *     size is greater than zero.
   */
  public void fire() throws IllegalActionException {
    ContinuousDirector dir = (ContinuousDirector) getDirector();
    double stepSize = dir.getCurrentStepSize();
    int microstep = dir.getIndex();

    if (_debugging) {
      Time currentTime = dir.getModelTime();
      _debug(
          "Fire at time "
              + currentTime
              + " and microstep "
              + microstep
              + " with step size "
              + stepSize);
    }
    // First handle the impulse input.
    if (impulse.getWidth() > 0 && impulse.hasToken(0)) {
      double impulseValue = ((DoubleToken) impulse.get(0)).doubleValue();
      if (_debugging) {
        _debug("-- impulse input received with value " + impulseValue);
      }
      if (impulseValue != 0.0) {
        if (microstep == 0) {
          throw new IllegalActionException(
              this, "Signal at the impulse port is not purely discrete.");
        }
        double currentState = getState() + impulseValue;
        setTentativeState(currentState);
        if (_debugging) {
          _debug("-- Due to impulse input, set state to " + currentState);
        }
      }
    }
    // Next handle the initialState port.
    ParameterPort initialStatePort = initialState.getPort();
    if (initialStatePort.getWidth() > 0 && initialStatePort.hasToken(0)) {
      double initialValue = ((DoubleToken) initialStatePort.get(0)).doubleValue();
      if (_debugging) {
        _debug("-- initialState input received with value " + initialValue);
      }
      if (microstep == 0.0) {
        throw new IllegalActionException(
            this, "Signal at the initialState port is not purely discrete.");
      }
      setTentativeState(initialValue);
      if (_debugging) {
        _debug("-- Due to initialState input, set state to " + initialValue);
      }
    }

    // Produce the current _tentativeState as output, if it
    // has not already been produced.
    if (!state.isKnown()) {
      double tentativeOutput = getTentativeState();
      // If the round has not updated since the last output, then
      // just produce the same output as last time.
      int currentRound = dir._getODESolver()._getRound();
      if (_lastRound == currentRound) {
        tentativeOutput = _lastOutput;
      }

      if (_debugging) {
        _debug("** Sending output " + tentativeOutput);
      }
      _lastOutput = tentativeOutput;
      state.broadcast(new DoubleToken(tentativeOutput));
    }

    // The _tentativeSate is committed only in postfire(),
    // but multiple rounds will occur before postfire() is called.
    // At each round, this fire() method may be called multiple
    // times, and we want to make sure that the integration step
    // only runs once in the step.
    if (derivative.isKnown() && derivative.hasToken(0)) {
      int currentRound = dir._getODESolver()._getRound();
      if (_lastRound < currentRound) {
        // This is the first fire() in a new round
        // where the derivative input is known and present.
        // Update the tentative state. Note that we will
        // have already produced an output, and so we
        // will not read the updated _tentativeState
        // again in subsequent invocations of fire()
        // in this round. So it is safe to update
        // _tentativeState.
        _lastRound = currentRound;
        double currentDerivative = getDerivative();
        if (Double.isNaN(currentDerivative) || Double.isInfinite(currentDerivative)) {
          throw new IllegalActionException(
              this, "The provided derivative input is invalid: " + currentDerivative);
        }
        if (stepSize > 0.0) {
          // The following method changes the tentative state.
          dir._getODESolver().integratorIntegrate(this);
        }
      }
    }
  }